I’ve been working on implementing the Quicksort algorithm in Java, but I seem to be encountering an issue where the array is not sorted correctly.
Here is my code:
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.quick_Sort(arr, 0, n-1);
System.out.println("Sorted array:");
printArray(arr);
}
void quick_Sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_Sort(arr, low, pi-1);
quick_Sort(arr, pi+1, high);
}
}
int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = (low-1);
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i;
}
static void printArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
I tried implementing the Quicksort algorithm with different pivot strategies (first element, last element, random element, median-of-three) and expected the array to be sorted correctly. However, the current implementation does not produce the expected sorted array.
I expected the array {10, 7, 8, 9, 1, 5} to be sorted into {1, 5, 7, 8, 9, 10}.
Can someone help me identify the issue with my Quicksort implementation? Specifically, I’m having trouble with the partition method.
3
Your partition method is incorrect: you are placing the pivot at index i + 1
yet returning i
which the caller assumes is the pivot index.