-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.java
53 lines (39 loc) · 1.18 KB
/
InsertionSort.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
package Algorithms.Sorting;
public class InsertionSort {
void sort(int[] unsortedArr) {
int len = unsortedArr.length;
for (int i = 1; i < len; ++i) {
int key = unsortedArr[i];
int j = i-1;
while (j >= 0 && unsortedArr[j] > key) {
unsortedArr[j + 1] = unsortedArr[j];
j = j-1;
}
unsortedArr[j+1] = key;
}
}
void recursiveSort(int[] unsortedArr, int n){
if (n == 0)
return;
int key = unsortedArr[n];
int j = n-1;
while (j >= 0 && unsortedArr[j] > key) {
unsortedArr[j + 1] = unsortedArr[j];
j = j-1;
}
unsortedArr[j+1] = key;
recursiveSort(unsortedArr, n-1);
}
void printArray(int[] arr) {
for (int i =0; i < arr.length ; i++){
System.out.print(arr[i]);
System.out.print(" ");
}
}
public static void main(String[] args) {
int[] arr = {1,9,4,6,2,2,0};
InsertionSort insertionSort = new InsertionSort();
insertionSort.recursiveSort(arr, arr.length-1);
insertionSort.printArray(arr);
}
}