【问题标题】:c++ bubble sort returning weird valuesc ++冒泡排序返回奇怪的值
【发布时间】:2016-11-06 23:23:17
【问题描述】:

我正在尝试使用冒泡排序对包含 10 个数字的数组进行排序。程序向用户询问 10 个数字,然后输出未排序的数组。这部分工作正常。然后它运行冒泡排序并输出排序后的数组。在我的测试中,我只输入了正整数,但是排序数组中的第一个值始终是一个非常小的数字,表示为“2.6812368e-317”或类似的东西。然后数组中的其余值出现在按应有的顺序排序的数字之后。排序后的数组显示 Windows 后,会出现一个错误,指出程序已停止工作。 我的代码如下:

int main(int argc, char** argv) {

double arrSort[10];// declare array to store numbers to be sorted

cout << "Please enter 10 numbers to be sorted" << endl;
// ask for values from user and input them in array
for (int i = 0; i < 10; i++)
    {
        cin >> arrSort[i];
    }

// display unsorted array
cout << "Unsorted Array: " << endl;
for (int i = 0; i < 10; i++)
    {
        if (i < 9)
            cout << arrSort[i] << ", ";
        else
            cout << arrSort[i] << endl;
    }

bool changed = true; // variable to store whether a change has been made
double temp; // variable to temporarily store a value while swapping

//start looping the array
do
{
    changed = false; // change to false so that if no changes are made to array the loop exits
    for (int i = 0; i < 10; i++) // start loop within array to check values
    {
        if (arrSort[i] > arrSort[i + 1]) // check if current index is greater than next index
        {
            // swap values
            temp = arrSort[i]; // store current index in temp variable
            arrSort[i] = arrSort[i + 1]; // assign next index to current index
            arrSort[i + 1] = temp; // assign temp value to next index

            changed = true; // set changed to true to run another loop
        }
    }
}while (changed); // if array was changed loop through again, if not changed exit loop

// output results of sorted array
cout << "Sorted Array: " << endl;
for (int i = 0; i < 10; i++)
{
    if (i < 9)
        cout << arrSort[i] << ", ";
    else
        cout << arrSort[i] << endl;
}
return 0;

}

这是程序测试运行的屏幕截图: Sorted Array output

【问题讨论】:

标签: c++ arrays sorting bubble-sort


【解决方案1】:
for (int i = 0; i < 10; i++) // <-- here's problem. 
{
    if (arrSort[i] > arrSort[i + 1]) 
    {
        // swap values
    }
}

i 变量应该小于 9 而不是 10。正如您在 if 语句中看到的那样,您正在检查 arrSort[i + 1],所以在最后一个元素中您是检查超出表格范围的数字(arrSort[10] 不存在)。我现在无法检查它,但我想这是问题所在。

【讨论】:

  • 太棒了!谢谢您的帮助。这样就解决了。现在看起来很明显。
【解决方案2】:

我认为问题出在这里:

if (arrSort[i] > arrSort[i + 1])

什么时候

i=9

您的数组有 10 个元素,您尝试比较

arrSort[9] > arrSort[9+1]

还有

arrSort[10]

不存在

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 2016-06-09
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2014-03-26
    • 2018-11-13
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多