c ++ bubble sort返回奇怪的值

时间:2016-11-06 23:23:17

标签: c++ arrays sorting bubble-sort

我正在尝试使用冒泡排序对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

2 个答案:

答案 0 :(得分: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]不存在)。我现在无法检查它,但我想这就是问题所在。

答案 1 :(得分:1)

我认为问题在于:

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

i=9

你的数组有10个元素,你试着比较

arrSort[9] > arrSort[9+1]

并且

arrSort[10]

不存在