因此,我尝试创建一个快速排序方法,但是,它不能正确排序。下面是我的输入和输出
原始数组:
80.0 10.0 50.0 70.0 60.0 90.0 20.0 30.0 40.0
排序数组:
0.0 30.0 20.0 80.0 40.0 60.0 70.0 10.0 90.0 50.0
我尝试将for循环更改为for(int i = left; i < right; i++)
但现在的输出是:
0.0 20.0 30.0 40.0 80.0 10.0 60.0 90.0 70.0 50.0
public static void sort(double[] a)
{
quickSort(a, 0, a.length-1);
}
public static void quickSort(double [] a, int left, int right)
{
if (left < right)
{
int pivotIndex = (left+right)/2;
int pos = partition(a,left,right,pivotIndex);
quickSort(a,left,pos-1);
quickSort(a,pos+1,right);
}
}
private static int partition(double [] a, int left,int right,int pivotIndex)
{
double temp = a[pivotIndex];
a[pivotIndex] = a[right];
a[right] = temp;
int pos = left;//represents boundary between small and large elements
for(int i = left; i < right-1; i++)
{
if (a[i] <= a[pivotIndex])
{
double temp2 = a[i];
a[i] = a[pos];
a[pos] = temp2;
pos++;
}
}
double temp3 = a[pivotIndex];
a[pivotIndex] = a[pos];
a[pos] = temp3;
return pos;
}发布于 2010-02-23 16:25:37
这就是你想要做的:
private static void swap(double[] a, int i, int j) {
double t = a[i];
a[i] = a[j];
a[j] = t;
}
private static int partition(double [] a, int left,int right,int pivotIndex)
{
swap(a, pivotIndex, right);
int pos = left;//represents boundary between small and large elements
for(int i = left; i < right; i++)
{
if (a[i] < a[right])
{
swap(a, i, pos);
pos++;
}
}
swap(a, right, pos);
return pos;
}我通过一个帮助器swap方法使代码更清晰。你在原始代码中有3个bug:
在循环中使用错误的索引来获取循环中的透视元素boundary
之后在错误的索引上交换了元素
发布于 2010-02-23 16:15:27
变化
for(int i = left; i < right-1; i++)至
for(int i = left; i < right; i++)https://stackoverflow.com/questions/2316555
复制相似问题