Skip to content

Commit d09fb80

Browse files
insertion sort
1 parent be2945c commit d09fb80

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed
1.25 MB
Binary file not shown.

lectures/11-sorting/code/src/com/kunal/Main.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,23 @@
55
public class Main {
66

77
public static void main(String[] args) {
8-
int[] arr = {4, 5, 1, 2, 3};
9-
selection(arr);
8+
int[] arr = {5, 3, 4, 1, 2};
9+
insertion(arr);
1010
System.out.println(Arrays.toString(arr));
1111
}
1212

13+
static void insertion(int[] arr) {
14+
for (int i = 0; i < arr.length - 1; i++) {
15+
for (int j = i+1; j > 0; j--) {
16+
if (arr[j] < arr[j-1]) {
17+
swap(arr, j, j-1);
18+
} else {
19+
break;
20+
}
21+
}
22+
}
23+
}
24+
1325
static void selection(int[] arr) {
1426
for (int i = 0; i < arr.length; i++) {
1527
// find the max item in the remaining array and swap with correct index

0 commit comments

Comments
 (0)