forked from Mystery-2-Dev/Java_Algorithms-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
27 lines (25 loc) · 842 Bytes
/
Copy pathInsertionSort.java
File metadata and controls
27 lines (25 loc) · 842 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Java program for implementation of Insertion Sort
class InsertionSort {
/*Function to sort array using insertion sort*/
public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int current = array[i];
int j = i - 1;
while(j >= 0 && current < array[j]) {
array[j+1] = array[j];
j--;
}
// at this point we've exited, so j is either -1
// or it's at the first element where current >= a[j]
array[j+1] = current;
}
}
public static void main(String args[]) {
int arr[] = { 12, 11, 13, 5, 6 };
InsertionSort insertionSort = new InsertionSort();
insertionSort.sort(arr);
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + ", ");
}
}
}