初级 C++ 学习者来求教,编程中排序题目遇到的问题,求解答
题目是用选择法对10个整数进行由小到大排序。我的编程是:
#include <iostream>
using namespace std;
int main()
{
void select_sort(int array[], int n);
int a[10], i;
cout << "输入原始数组:" << endl;
for (i = 0; i < 10; i++)
cin >> a[i];
cout << endl;
select_sort(a, 10);
cout << "排序好的数组:" << endl;
for (i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
void select_sort(int array[], int n)
{
int i, j, t;
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < n;j++)
if (array[j] < array[i])
t = array[j]; array[j] = array[i]; array[i] = t;
参考答案给的编程:
#include <iostream>
using namespace std;
int main()
{
void select_sort(int array[], int n);
int a[10], i;
cout << "输入原始数组:" << endl;
for (i = 0; i < 10; i++)
cin >> a[i];
cout << endl;
select_sort(a, 10);
cout << "排序好的数组:" << endl;
for (i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
void select_sort(int array[], int n)
{
int i, j,k, t;
for (i = 0; i < 10; i++)
{
k = i;
for (j = i + 1; j < n;j++)
if (array[j] < array[i])
k = j;
t = array[k]; array[k] = array[i]; array[i] = t;
}
}
不同点在于红色标记的地方。我的编程没有设置变量K,但是答案设置了。我个人觉得有没有K都无所谓啊,但是实际运行我的是错误的,答案是正确的。我很想知道这个K起到什么作用?为什么非要弄个K呢?求大神的详细解答啊