I am trying to learn Quick Sort algorithm and this is my code so far:
import java.util.Arrays;
public class JavaFiddle {
static int[] myArray = new int[]{35, 12, 25, 1, 5, 33, 56};
public static void QuickSort(int[] array) {
QuickSort(array, 0, array.length - 1);
}
public static void QuickSort(int[] array, int left, int right) {
if (left < right) {
int pivot = left + ((right - left) / 2);
int index = partition(array, left, right, pivot);
QuickSort(array, left, index - 1);
QuickSort(array, index + 1, right);
}
}
public static int partition(int[] array, int left, int right, int pivot) {
while (left < right) {
while (array[left] < pivot) {
left++;
}
while (array[right] > pivot) {
right--;
}
if (left < right) {
swap(array, left, right);
left++;
right--;
}
}
return left;
}
public static void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(myArray));
QuickSort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
However, this code gives me an incorrect result:
[35, 12, 25, 1, 5, 33, 56] - before sort
[1, 12, 25, 35, 5, 33, 56] - after sort
What do I have wrong here? I cannot find the flaw in the logic.
printlnat the beginning ofQuickSortto print the subarray betweenleftandright, so you can find out exactly when something unexpected happens?