Skip to content

Commit

Permalink
fix quick sort partition for special inputs and update testcase (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hearen authored and pedrovgs committed Apr 14, 2019
1 parent 4e22141 commit ed6f8a4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/main/java/com/github/pedrovgs/problem80/QuickSort.java
Expand Up @@ -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;
}
}
Expand Up @@ -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);
}
}

0 comments on commit ed6f8a4

Please sign in to comment.