【发布时间】: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