Sorting 快速排序逻辑
我试图在java中实现快速排序,我有一个疑问。下面是我的快速排序代码:Sorting 快速排序逻辑,sorting,quicksort,Sorting,Quicksort,我试图在java中实现快速排序,我有一个疑问。下面是我的快速排序代码: package com.sorting; public class QuickSort implements Sort { @Override public int [] sort(int[] arr) { return quickSort(arr, 0, arr.length - 1); } private int [] quickSort(int[] numbers, int low, int high)
package com.sorting;
public class QuickSort implements Sort {
@Override
public int [] sort(int[] arr) {
return quickSort(arr, 0, arr.length - 1);
}
private int [] quickSort(int[] numbers, int low, int high) {
if (low < high) {
int q = partitionTheArrayAroundPivot(numbers, low, high);
if (low < q)
quickSort(numbers, low, q);
if ((q+1) < high)
quickSort(numbers, q + 1, high);
}
return numbers;
}
private int partitionTheArrayAroundPivot(int[] numbers, int low, int high) {
int pivot = selectPivot(numbers, low, high);
int i = low;
int j = high;
while (true) {
while (numbers[i] < pivot) {
i++;
}
while (numbers[j] > pivot) {
j--;
}
if ( i <= j) {
swap(numbers, i, j);
i++;
j--;
} else {
return j;
}
}
}
private int selectPivot(int[] numbers, int low, int high) {
return numbers[high];
}
private void swap(int[] numbers, int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
因此,这意味着两个索引也将从循环中出来,如果两个索引都在两个不同的位置命中枢轴,例如,这里的1,0,1如果枢轴为1,那么i为0,j为2。并满足以下条件
如果(i我会稍微重写代码,以便selectPivot返回索引:
private int selectPivotIndex(int[] numbers, int low, int high) {
return high;
}
然后,分区函数可以将数据透视移到一边,并根据数据透视值对其余项目进行排序。单循环即可完成此操作,在此实现中,重复的数据透视将在右侧结束:
private int partitionTheArrayAroundPivot(int[] numbers, int low, int high) {
int pivotIndex = selectPivotIndex(numbers, low, high);
swap(numbers, pivotIndex, high); // Not needed if selectPivotIndex always returns high
int newPivotIndex = low;
for(int i = low; i < high; i++)
{
if(numbers[i] < numbers[pivotIndex])
{
swap(numbers, i, newPivotIndex);
newPivotIndex++;
}
}
swap(numbers, newPivotIndex, pivotIndex);
return newPivotIndex;
}
这种方法更容易理解和调试,希望对您有用。使用while(数字[i]=pivot)
你的代码会工作我不明白这个问题。你是在问你的代码是否工作?还是在问你的代码为什么工作?或者其他什么?我的代码不适用于我上面提到的情况…那么代码中有什么问题…在这种情况下,你应该使用调试器逐步检查代码,找出为什么不工作我调试了它,然后才知道场景{1,0,1},其中pivot为1,它失败了…那么如何在快速排序算法中处理这些场景呢?你在我的回答中尝试过代码了吗?
private int selectPivotIndex(int[] numbers, int low, int high) {
return high;
}
private int partitionTheArrayAroundPivot(int[] numbers, int low, int high) {
int pivotIndex = selectPivotIndex(numbers, low, high);
swap(numbers, pivotIndex, high); // Not needed if selectPivotIndex always returns high
int newPivotIndex = low;
for(int i = low; i < high; i++)
{
if(numbers[i] < numbers[pivotIndex])
{
swap(numbers, i, newPivotIndex);
newPivotIndex++;
}
}
swap(numbers, newPivotIndex, pivotIndex);
return newPivotIndex;
}
if (low < q)
quickSort(numbers, low, q - 1);