-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
34 lines (25 loc) · 847 Bytes
/
InsertionSort.java
File metadata and controls
34 lines (25 loc) · 847 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
package DataStructure;
import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {2,6,1,9,3,0,24,11};
System.out.println("before" + Arrays.toString(arr));
System.out.printf("after" + Arrays.toString(sort(arr)));
}
public static int[] sort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
return arr;
}
}