我试图实现快速排序算法,但我有困难做它。我认为问题是在分区方法中,我把数组的第一个元素作为枢轴,并且我使用一个指针,它把所有较小的值放在数组的左边,最后把枢轴放在中间。谢谢您。
我的输入是:{42,12,52,1,34,31,0,3}但是我得到了: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;
}
2条答案
按热度按时间dohp0rv51#
哦,我明白了,我只需要把代码的一部分放在for循环的中间。
cidc1ykv2#
有
int pointer = A[high]
并添加int i = (low - 1)
其中它是较小元素的索引。