C++ 中的选择排序无法正常工作
Selection Sorting in C++ not working correctly
我做的是选择排序,完全运行但是结果不正确。
这是我的代码:
#include<iostream>
using namespace std;
int main()
{
int array[5], temp, min, i, j;
for(i = 0; i <= 4; i++)
{
cout << "Enter the value"<<endl;
cin >> array[i];
}
cout << "Values before sorting:" << endl;
for(i = 0; i <= 4; i++)
cout << array[i] << " ";
cout << endl;
for(i = 0; i <= 4; i++)
{
min = i;
for(j = i + 1; j <= 4; j++)
{
if(array[j] < array[min])
min = j;
if(min != i)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
cout << "values after sorting" << endl;
for(i = 0; i <= 4; i++)
cout << array[i] << " ";
}
}
谁能告诉我我的代码有什么错误
错误在于您在找到最小值后更新数组的方式。
在每次迭代中,你应该找到 array[i]..array[4] 之间的最小值,然后你需要将 array[i] 与 array[min] 交换如下:
#include<iostream>
using namespace std;
int main() {
int array[5],temp,min,i,j;
for(i=0;i<=4;i++)
{
cout<<"Enter the value"<<endl;
cin>>array[i];
}
cout<<"values before sorting"<<endl;
for(i=0;i<=4;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
for (i = 0; i <= 4; i++)
{
min = i;
for (j = i + 1; j <= 4; j++)
{
if (array[j] < array[min])
{
min = j;
}
}
if (min != i)
{
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
cout << "values after sorting" << endl;
for (i = 0; i <= 4; i++)
{
cout << array[i] << " ";
}
}
我做的是选择排序,完全运行但是结果不正确。
这是我的代码:
#include<iostream>
using namespace std;
int main()
{
int array[5], temp, min, i, j;
for(i = 0; i <= 4; i++)
{
cout << "Enter the value"<<endl;
cin >> array[i];
}
cout << "Values before sorting:" << endl;
for(i = 0; i <= 4; i++)
cout << array[i] << " ";
cout << endl;
for(i = 0; i <= 4; i++)
{
min = i;
for(j = i + 1; j <= 4; j++)
{
if(array[j] < array[min])
min = j;
if(min != i)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
cout << "values after sorting" << endl;
for(i = 0; i <= 4; i++)
cout << array[i] << " ";
}
}
谁能告诉我我的代码有什么错误
错误在于您在找到最小值后更新数组的方式。 在每次迭代中,你应该找到 array[i]..array[4] 之间的最小值,然后你需要将 array[i] 与 array[min] 交换如下:
#include<iostream>
using namespace std;
int main() {
int array[5],temp,min,i,j;
for(i=0;i<=4;i++)
{
cout<<"Enter the value"<<endl;
cin>>array[i];
}
cout<<"values before sorting"<<endl;
for(i=0;i<=4;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
for (i = 0; i <= 4; i++)
{
min = i;
for (j = i + 1; j <= 4; j++)
{
if (array[j] < array[min])
{
min = j;
}
}
if (min != i)
{
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
cout << "values after sorting" << endl;
for (i = 0; i <= 4; i++)
{
cout << array[i] << " ";
}
}