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

C++ 为什么我的排序算法会更改数组值?,c++,algorithm,sorting,bubble-sort,C++,Algorithm,Sorting,Bubble Sort,这是一个简单的冒泡排序算法,是我的大型程序的一部分,用于对一个双精度数组进行排序。我以前尝试过用merge-sort对相同的值进行排序,但得到了相同的输出。我真的没有注意到我遗漏了什么。有人能告诉我吗 提前谢谢 #include<iostream> #include<iomanip> using namespace std; int const POINTS = 5; double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2,

这是一个简单的冒泡排序算法,是我的大型程序的一部分,用于对一个双精度数组进行排序。我以前尝试过用merge-sort对相同的值进行排序,但得到了相同的输出。我真的没有注意到我遗漏了什么。有人能告诉我吗 提前谢谢

#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] << " ";
    }

}
可以使用int类型的临时变量交换double

改用:

double temp;
或更好的自动:

或者更好地使用std::swap:

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

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

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

使用调试器的好机会。。。。这是阅读和修复编译器警告的好机会。您应该会收到一条关于doublt-to-int转换的警告,这会直接导致问题的出现。请将int-temp更改为double-temp…同时,避免使用全局变量。作为参数传递点。我对点很敏感。这是一个全球性的,但它也是恒定的。很难搞乱一个常数。如果你想改变排序算法,最好传递一个std::vector.Holy!非常感谢。那是一个愚蠢的错误,我为此伤了好几个小时的脑筋。我需要睡觉。
const auto temp = dataPoints[j];             
dataPoints[j] = dataPoints[j + 1];
dataPoints[j + 1] = temp;
std::swap(dataPoints[j], dataPoints[j + 1]);
std::sort(std::begin(dataPoints), std::end(dataPoints), std::greater<>{});