appxsl 于 2014.10.09 17:18 提问

#include
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
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呢？求大神的详细解答啊
``````

1个回答

ZHUJIANWEILI4   2014.10.09 21:09

#include
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]) 这里应该是把array[i]该为array[k]的
k = j;
t = array[k]; array[k] = array[i]; array[i] = t;
}
}

for(j=i+1;j<n;j++)
{
for(array[j]<array[i])
{
t = array[j]; array[j] = array[i]; array[i] = t;
}
}