diff --git a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java index ca2899f9..af8d1627 100644 --- a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java +++ b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java @@ -57,19 +57,13 @@ private void quickSort(int[] numbers, int left, int right) { private int partition(int[] numbers, int left, int right) { int pivot = numbers[right]; - while (left < right) { - while (numbers[left] < pivot) { - left++; - } - while (numbers[right] > pivot) { - right--; - } - if (left <= right) { - int temp = numbers[left]; - numbers[left] = numbers[right]; - numbers[right] = temp; + int i = left - 1; + for (int j = left; j < right; ++j) { + if (numbers[j] <= pivot) { + swap(numbers, ++i, j); } } - return left; //pivot index + swap(numbers, ++i, right); + return i; } } diff --git a/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java b/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java index f57e22d1..59e70cbe 100644 --- a/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java +++ b/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java @@ -79,4 +79,15 @@ public abstract class SortingAlgorithmTest { int[] expectedArray = { 1, 2, 3, 4 }; assertArrayEquals(expectedArray, input); } + + @Test(timeout = 5 * 1000) + public void shouldSortSpecialArray() { + int[] input = {12, -37, -5, 43, 62, 45, -95, -70, -55, -62, -24, -14, + -75, 43, 9, 58, -62, -22, -55}; + + sortingAlgorithm.sort(input); + + int[] expectedArray = {-95, -75, -70, -62, -62, -55, -55, -37, -24, -22, -14, -5, 9, 12, 43, 43, 45, 58, 62}; + assertArrayEquals(expectedArray, input); + } }