【发布时间】:2020-02-18 17:21:01
【问题描述】:
这是一个简单的冒泡排序算法,是我较大程序的一部分,旨在对双精度数组进行排序。我之前尝试使用合并排序对相同的值进行排序,但得到了相同的输出。我真的没有注意到我错过了什么。有人可以向我指出吗 提前致谢!
#include<iostream>
#include<iomanip>
using namespace std;
int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };
void sort(double dataPoints[])
{
int i, j, flag = 1;
int temp;
for (i = 1; (i <= POINTS) && flag; i++)
{
flag = 0;
for (j = 0; j < (POINTS - 1); j++)
{
if (dataPoints[j + 1] > dataPoints[j])
{
temp = dataPoints[j];
dataPoints[j] = dataPoints[j + 1];
dataPoints[j + 1] = temp;
flag = 1;
}
}
}
}
int main()
{
sort(dataPoints);
for (int i = 0; i < POINTS; i++)
{
cout << dataPoints[i] << " ";
}
}
Output:
0.8 0 0 0 0
【问题讨论】:
-
使用调试器的好机会。
-
... 以及阅读和修复编译器警告的好机会。您应该会收到有关 doublt-to-int 转换的警告,这会直接导致您遇到问题。
-
把
int temp改成double temp... -
另外,避免使用全局变量。将 POINTS 作为参数传递。
-
我很喜欢
POINTS。这是一个全球性的,但它也是恒定的。很难搞砸一个常数。如果您想改变排序算法,最好传递std::vector。
标签: c++ algorithm sorting bubble-sort