我正在尝试以降序实现QuickSort。我试图追溯我的代码,以了解为什么它只是部分排序。我的输入是一个{3,4,6,1,9,7}的整数数组。排序后,我得到{9,4,7,6,3,1},其中4不在正确的位置。
public int partition(int arr[], int left, int right)
{
int pivot = arr[right];
int i = left - 1;
for(int j = right; j >= left; j--)
{
if (arr[j] > pivot)
{
i = i + 1;
int temp = arr[i];
arr[i]= arr[j];
arr[j]= temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[right];
arr[right] = temp;
return i + 1;
}
public void sorting(int arr[], int left, int right)
{
if(left < right)
{
int q = partition(arr, left, right);
sorting(arr, left, q - 1);
sorting(arr, q + 1, right);
}
}
答案 0 :(得分:0)
您的代码应如下所示:
public int partition(int arr[], int left, int right){
int pivot = arr[left];
int i = left;
for(int j = left + 1; j <= right; j++){
if (arr[j] > pivot){
i = i + 1;
int temp = arr[i];
arr[i]= arr[j];
arr[j]= temp;
}
}
int temp = arr[i];
arr[i] = arr[left];
arr[left] = temp;
return i;
}
public void sorting(int arr[], int left, int right){
if(left < right)
{
int q = partition(arr, left, right);
sorting(arr, left, q);
sorting(arr, q + 1, right);
}
}
答案 1 :(得分:0)
您的方法是正确的,但需要进行一些修改 请查看以下代码以更正您的结果。
public static void quickSort(int[] ar, int start, int end) {
if (start <end) {
int p = partition(ar, start, end);
quickSort(ar, start, p-1);
quickSort(ar, p+1, end);
}
}
public static int partition(int[] ar, int start, int end) {
int pivot = ar[end];
int i = start;
for (int j = end; j>= start; j--) {
if (ar[j] > pivot) {
int temp1 = ar[i];
ar[i] = ar[j];
ar[j] = temp1;
i = i+1;
}
}
int temp2 = ar[i];
ar[i] = ar[end];
ar[end] = temp2;
return i;
}