问题描述
我正在尝试实现QuickSort算法,但是在执行时遇到了麻烦。我认为问题在于分区方法,在该方法中,我将数组的第一个元素作为枢轴,并使用了一个指针,该指针将所有较小的值置于数组的左侧,最后将枢轴置于中间。谢谢。
我的输入是:{42,12,52,1,34,31,3} 但我得到:12、31、1、42、0、3、52、34
public static void quickSort(int[] A) {
quickSort(A,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,p - 1);
quickSort(A,p + 1,high);
}
return A;
}
private static int partition(int[] A,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;
}
解决方法
哦,我明白了,我只需要将代码的一部分放在将支点放在for循环之外的中间位置即可。
,具有int pointer = A[high]
并在小元素的索引处添加int i = (low - 1)
。
void quickSort(int[] A,int low,int high) {
if (low < high) {
int p = partition(A,low,high);
quickSort(A,p - 1);
quickSort(A,p + 1,high);
}
}
int partition(int A[],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;
}