-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathInsertionSort.java
More file actions
53 lines (43 loc) · 1.21 KB
/
InsertionSort.java
File metadata and controls
53 lines (43 loc) · 1.21 KB
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
/**
* InsertionSort: for every element in the array, insert it into sorted sequence iteratively.
*
* Time Complexity: O(n^2).
* Space Complexity: O(1).
*
*/
import java.util.Arrays;
public class InsertionSort {
public static void sort(int[] arr) {
for (int i=1; i < arr.length; i++) {
int curr = arr[i];
int j = i-1;
while (j >= 0 && arr[j] > curr) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = curr;
}
}
public static void sort(Integer[] arr) {
for (int i=1; i < arr.length; i++) {
int curr = arr[i];
int j = i-1;
while (j >= 0 && arr[j] > curr) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = curr;
}
}
public static void main(String[] args) {
int[] arr1 = {10, 3, 7, 5, 1, 15, 20};
InsertionSort.sort(arr1);
System.out.println(Arrays.toString(arr1));
int[] arr2 = {};
InsertionSort.sort(arr2);
System.out.println(Arrays.toString(arr2));
int[] arr3 = {10};
InsertionSort.sort(arr3);
System.out.println(Arrays.toString(arr3));
}
}