-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
40 lines (35 loc) · 852 Bytes
/
InsertionSort.java
File metadata and controls
40 lines (35 loc) · 852 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
28
29
30
31
32
33
34
35
36
37
38
39
40
public class InsertionSort {
public int[] sort(int a[]) {
int N = a.length;
//Start the i pointer and move toward right.
for(int i=0;i<N;i++) {
//Start j pointer from same position as i and move towards left to compare and exchange.
for(int j=i;j>0;j--) {
if(less(a[j],a[j-1])) {
exch(a,j,j-1);
}
else {
break;
}
}
}
return a;
}
private boolean less(int a, int b) {
return a<b;
}
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
public static void main(String[] args) {
int[] array = {7,10,5,3,8,4,2,9,6};
InsertionSort is = new InsertionSort();
int sortedArray[] = is.sort(array);
for(int i =0; i<array.length;i++) {
System.out.print(sortedArray[i]);
System.out.print(" ");
}
}
}