Shell sort (#7391)

* Shell sort

* Add new line at the end
This commit is contained in:
cdjole 2019-07-23 07:36:04 +02:00 committed by maibin
parent 4bf6b77067
commit dd0003a478
2 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.shellsort;
public class ShellSort {
public static void sort(int arrayToSort[]) {
int n = arrayToSort.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = arrayToSort[i];
int j = i;
while (j >= gap && arrayToSort[j - gap] > key) {
arrayToSort[j] = arrayToSort[j - gap];
j -= gap;
}
arrayToSort[j] = key;
}
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.shellsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ShellSortUnitTest {
@Test
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
ShellSort.sort(input);
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
assertArrayEquals("the two arrays are not equal", expected, input);
}
}