gpt4 book ai didi

c++ - 使用 double 值实现快速排序

转载 作者:行者123 更新时间:2023-11-28 01:02:18 24 4
gpt4 key购买 nike

我必须创建一个程序,它接受一个包含未排序数字的输入文件,并使用快速排序输出另一个包含已排序数字的文件。该程序在使用整数的多个测试用例下运行良好。但是,当我将数组格式从“int”更改为“double”时,我的程序无法正确排序值。最让我困惑的是它不一致。例如,输入“5,4,3,2,2.1”工作正常,但输入“5,4,3,2.2,2.1”导致段错误。任何帮助,将不胜感激。谢谢。

void swap(double *x, double *y)
{
double tmp;
tmp = *x;
*x = *y;
*y = tmp;
}

int pivot(int i, int j)
{
return ((i+j)/2);
}

void quickSort(double values[], int low, int high)
{
int start;
int end;
int k;
int p;


if (low < high)
{
p = pivot(low,high);
swap(&values[low],&values[p]);
k = values[low];
start = (low+1);
end = high;

while (start <= end)
{
while ((start <= high) && (values[start] <= k))
{
start++;
}
while ((end >= low) && (values[end] > k))
{
end--;
}
if (start < end)
{
swap(&values[start],&values[end]);
}
}
swap(&values[low],&values[end]);
quickSort(values,low,(end-1));
quickSort(values,(end+1),high);
}
}

int main()
{
...
quickSort(array, 0, (size+1);
...
return 0;
}

最佳答案

我认为 k 在这里应该是一个双数 :)

关于c++ - 使用 double 值实现快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117070/

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