C++ 中的选择排序(已修改)不适用于所有情况
Selection sort in C++ (modified) not working for all cases
我正在尝试修改 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 作为数组,我会得到与输入相同的数组作为输出。请告诉我我的代码有什么问题。
问题是因为交换逻辑的错误位置。交换应该放在内部循环之外。
#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;
}
现在这给出了预期的输出。
我正在尝试修改 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 作为数组,我会得到与输入相同的数组作为输出。请告诉我我的代码有什么问题。
问题是因为交换逻辑的错误位置。交换应该放在内部循环之外。
#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;
}
现在这给出了预期的输出。