I am trying to implement the QuickSort algorithm but I am having trouble doing it. I think the problem is with the partitioning method where I make the first element of the array as the pivot and I use a pointer that puts all the smaller values to the left of the array, and lastly putting the pivot in the middle. Thank you.
My input is: {42,12,52,1,34,31,0,3} But I am getting: 12, 31, 1, 42, 0, 3, 52, 34
public static void quickSort(int[] A) {
quickSort(A, 0, A.length - 1);
}
private static int[] quickSort(int[] A, int low, int high) {
if (low < high) { // if there is still at least 1 element left in the array
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
}
return A;
}
private static int partition(int[] A, int low, int high) {
int pointer = low + 1;
int temp = 0;
for (int i = low + 1; i <= high; i++) {
if (A[i] < A[low]) { // if a num is less than pivot, then put to left
temp = A[pointer];
A[pointer] = A[i];
A[i] = temp;
pointer++;
}
temp = A[pointer - 1];
A[pointer - 1] = A[low];
A[low] = temp;
}
return pointer - 1;
}
Oh I got it, I just need to put the part of the code where I place the pivot in the middle outside of the for loop.
Have int pointer = A[high]
and add int i = (low - 1)
where it is the index of the smaller element.
void quickSort(int[] A, int low, int high) {
if (low < high) {
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
}
}
int partition(int A[], int low, int high) {
int pointer = A[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (A[j] <= pointer) {
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[high];
A[high] = temp;
return i + 1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.