[英]QuickSort java implementation
I am trying to implement the QuickSort algorithm but I am having trouble doing it.我正在尝试实现 QuickSort 算法,但在执行时遇到了问题。 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.
我认为问题出在分区方法上,我将数组的第一个元素设为 pivot,并使用一个指针将所有较小的值放在数组的左侧,最后将 pivot 放在中间。 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我的输入是:{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;
}
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.哦,我明白了,我只需要将我放置 pivot 的代码部分放在 for 循环之外的中间。
Have int pointer = A[high]
and add int i = (low - 1)
where it is the index of the smaller element.有
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, 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.