【问题标题】:Selection sort in C++ (modified) not working for all casesC ++(修改)中的选择排序不适用于所有情况
【发布时间】:2020-10-14 06:24:38
【问题描述】:

我试图在 C++ 中修改选择排序代码以检查结果。我修改后的代码是:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cout<<"Enter number of elements\n";
    cin>>n;
    int i,j,small,pos,t;
    int a[n];
    cout<<"Enter elements of array\n";
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<n-1;i++)
    {
        small=a[i];
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(a[j]<small)
            {
                small=a[j];
                pos=j;
            }
            t=a[i];
            a[i]=a[pos];
            a[pos]=t;
        }
    }
    cout<<"Sorted array:\n";
    for(i=0;i<n;i++)
    cout<<a[i]<<" ";
    return 0;
}

此代码适用于某些数组,但不适用于其他数组。 例如:如果我输入 1,11,2,22,3 作为数组,我会得到正确的输出:1,2,3,11,22。但是,如果我输入 1,11,2,22,3,33 作为数组,我会得到与输入相同的数组作为输出。请告诉我我的代码有什么问题。

【问题讨论】:

标签: c++ sorting selection-sort


【解决方案1】:

问题是由于交换逻辑的位置错误。交换应放置在内循环之外。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cout<<"Enter number of elements\n";
    cin>>n;
    int i,j,small,pos,t;
    int a[n];
    cout<<"Enter elements of array\n";
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<n-1;i++)
    {
        small=a[i];
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(a[j]<small)
            {
                small=a[j];
                pos=j;
            }
        }
        //Swap here
        t=a[i];
        a[i]=a[pos];
        a[pos]=t;
    }
    cout<<"Sorted array:\n";
    for(i=0;i<n;i++)
    cout<<a[i]<<" ";
    return 0;
}

现在这给出了预期的输出。

【讨论】:

  • 是的,我试图看看如果我在“内部”循环中交换会发生什么。您能告诉我在“内部”循环中交换会出现什么问题吗?
  • 选择排序通过从子数组的其余部分(最初是完整的数组)中选择最小元素并通过交换将最小元素移动到开头来工作。选择这里错误的最小元素时不能执行交换。
猜你喜欢
  • 2021-11-03
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 2012-02-18
相关资源
最近更新 更多