Skip to content

Commit d385e7b

Browse files
authored
Merge pull request eugenp#5398 from moisko/master
BAEL-2212: Insertion Sort in Java
2 parents 6d67e16 + 178c943 commit d385e7b

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.algorithms.insertionsort;
2+
3+
public class InsertionSort {
4+
5+
public static void insertionSortImperative(int[] input) {
6+
for (int i = 1; i < input.length; i++) {
7+
int key = input[i];
8+
int j = i - 1;
9+
while (j >= 0 && input[j] > key) {
10+
input[j + 1] = input[j];
11+
j = j - 1;
12+
}
13+
input[j + 1] = key;
14+
}
15+
}
16+
17+
public static void insertionSortRecursive(int[] input) {
18+
insertionSortRecursive(input, input.length);
19+
}
20+
21+
private static void insertionSortRecursive(int[] input, int i) {
22+
// base case
23+
if (i <= 1) {
24+
return;
25+
}
26+
27+
// sort the first i - 1 elements of the array
28+
insertionSortRecursive(input, i - 1);
29+
30+
// then find the correct position of the element at position i
31+
int key = input[i - 1];
32+
int j = i - 2;
33+
// shifting the elements from their position by 1
34+
while (j >= 0 && input[j] > key) {
35+
input[j + 1] = input[j];
36+
j = j - 1;
37+
}
38+
// inserting the key at the appropriate position
39+
input[j + 1] = key;
40+
}
41+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package algorithms.insertionsort;
2+
3+
import com.baeldung.algorithms.insertionsort.InsertionSort;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.assertArrayEquals;
7+
8+
public class InsertionSortUnitTest {
9+
10+
@Test
11+
public void givenUnsortedArray_whenInsertionSortImperatively_thenItIsSortedInAscendingOrder() {
12+
int[] input = {6, 2, 3, 4, 5, 1};
13+
InsertionSort.insertionSortImperative(input);
14+
int[] expected = {1, 2, 3, 4, 5, 6};
15+
assertArrayEquals("the two arrays are not equal", expected, input);
16+
}
17+
18+
@Test
19+
public void givenUnsortedArray_whenInsertionSortRecursively_thenItIsSortedInAscendingOrder() {
20+
// int[] input = {6, 4, 5, 2, 3, 1};
21+
int[] input = {6, 4};
22+
InsertionSort.insertionSortRecursive(input);
23+
int[] expected = {1, 2, 3, 4, 5, 6};
24+
assertArrayEquals("the two arrays are not equal", expected, input);
25+
}
26+
}

0 commit comments

Comments
 (0)