提问者:小点点

选择排序程序排序不正确[已关闭]


#include <iostream>

using namespace std;

int main()
{
    int n, arr[10], i, j, temp, minin;
    cin >> n;
    for (i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    for (i = 0; i < n - 1; i++)
    {
        minin = i;
        for (j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[minin])
                minin = j;
            temp = arr[minin];
            arr[minin] = arr[i];
            arr[i] = temp;
        }
    }
    for (i = 0; i < n; i++)
    {
        cout << arr[i];
    }
    return 0;
}

没有编译时错误。 但我的代码排序不正确。

这就是我得到的:

输入:

4 //size of the array to be sorted
5 3 2 8 //actual array to be sorted

输出:

3528

预期的输出是按升序排序的数组。


共1个答案

匿名用户

在我看来(根本没有测试),您需要将交换代码移出内部循环

而不是您的代码

for(j=i+1;j<n;j++)
{
    if(arr[j]<arr[minin])
        minin=j;
    temp=arr[minin];
    arr[minin]=arr[i];
    arr[i]=temp;
}

但取而代之的是

// calculate the index of the minimum element in the rest of the array
for(j=i+1;j<n;j++)
{
    if(arr[j]<arr[minin])
       minin=j;
}
// swap the minimum element with the current element
temp=arr[minin];
arr[minin]=arr[i];
arr[i]=temp;

您应该首先计算最小索引,然后用i交换最小索引。 这些任务应该是分开的,你的代码把它们搞混了。