Merge pull request #5398 from moisko/master

BAEL-2212: Insertion Sort in Java
This commit is contained in:
Loredana Crusoveanu 2018-10-09 12:58:32 +03:00 committed by GitHub
commit d385e7bbf5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.baeldung.algorithms.insertionsort;
public class InsertionSort {
public static void insertionSortImperative(int[] input) {
for (int i = 1; i < input.length; i++) {
int key = input[i];
int j = i - 1;
while (j >= 0 && input[j] > key) {
input[j + 1] = input[j];
j = j - 1;
}
input[j + 1] = key;
}
}
public static void insertionSortRecursive(int[] input) {
insertionSortRecursive(input, input.length);
}
private static void insertionSortRecursive(int[] input, int i) {
// base case
if (i <= 1) {
return;
}
// sort the first i - 1 elements of the array
insertionSortRecursive(input, i - 1);
// then find the correct position of the element at position i
int key = input[i - 1];
int j = i - 2;
// shifting the elements from their position by 1
while (j >= 0 && input[j] > key) {
input[j + 1] = input[j];
j = j - 1;
}
// inserting the key at the appropriate position
input[j + 1] = key;
}
}

View File

@ -0,0 +1,26 @@
package algorithms.insertionsort;
import com.baeldung.algorithms.insertionsort.InsertionSort;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class InsertionSortUnitTest {
@Test
public void givenUnsortedArray_whenInsertionSortImperatively_thenItIsSortedInAscendingOrder() {
int[] input = {6, 2, 3, 4, 5, 1};
InsertionSort.insertionSortImperative(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
}
@Test
public void givenUnsortedArray_whenInsertionSortRecursively_thenItIsSortedInAscendingOrder() {
// int[] input = {6, 4, 5, 2, 3, 1};
int[] input = {6, 4};
InsertionSort.insertionSortRecursive(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
}
}