gpt4 book ai didi

java - 快速排序不排序

转载 作者:行者123 更新时间:2023-12-03 02:23:18 25 4
gpt4 key购买 nike

所以我试图创建一个快速排序方法,但是,它没有正确排序。这是我的输入和输出
原始数组:
80.0 10.0 50.0 70.0 60.0 90.0 20.0 30.0 40.0 0.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;
}

最佳答案

这就是你想要做的:

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 个错误:

  • 循环边界上的一次性误差
  • 您使用了错误的索引来获取循环中的枢轴元素
  • 循环后交换了错误索引处的元素

关于java - 快速排序不排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2316555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com