为什么我的排序算法会更改数组值

Why is my sort algorithm changing the array values?

本文关键字:数组 我的 排序 算法 为什么      更新时间:2023-10-16

这是一个简单的冒泡排序算法,是我的大型程序的一部分,旨在对doubles数组进行排序。我以前尝试过用合并排序对相同的值进行排序,但得到了相同的输出。我真的没有注意到我错过了什么。有人能给我指一下吗提前感谢!

#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  

double与类型为int的临时进行交换。

改为使用:

double temp;

或更好的auto:

const auto temp = dataPoints[j];             
dataPoints[j] = dataPoints[j + 1];
dataPoints[j + 1] = temp;

甚至更好,使用std::swap:

std::swap(dataPoints[j], dataPoints[j + 1]);

如果允许,您甚至可以使用:

std::sort(std::begin(dataPoints), std::end(dataPoints), std::greater<>{});

将临时变量的数据类型更改为double。

相关文章: