【问题标题】:Why is my sort algorithm changing the array values?为什么我的排序算法会更改数组值?
【发布时间】: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


【解决方案1】:

您将doubleint 类型的临时交换。

改用:

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<>{});

【讨论】:

  • 神圣!谢谢!这是一个愚蠢的错误,我为此头疼了好几个小时。我需要睡觉。
【解决方案2】:

将临时变量的数据类型更改为双精度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2013-10-08
    • 2020-06-20
    • 1970-01-01
    • 2017-03-27
    • 2020-09-04
    相关资源
    最近更新 更多