Problem Description
编写程序,输入一串整数(把这串整数存储在数组中),然后通过调用selection_sort函数来排序这些整数。
在给定n个元素的数组后,selection_sort函数必须做下列工作:
(1)搜索数组找出最大元素,然后把它移到数组的最后;
(2)递归地调用函数本身来对前n-1个数组元素进行排序。
测试程序为:
#include <stdio.h>
#define N 100
void selection_sort(int a[], int len);
int main()
{
int a[N], i = 0, len;
while (scanf("%d", &a[i]) == 1)
{
i++;
}
len = i;
selection_sort(a, len);
for (i = 0; i < len; i++)
{
if (i == 0) printf("%d", a[i]);
else printf(" %d", a[i]);
}
printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
Input Description
在一行中输入一串整数(不超过100个整数),整数之间以空格分隔。
Output Description
在一行中输出排序后的整数,相互之间用空格分隔,注意最后一个整数之后没有空格。
Sample Input
9 8 7 6 5 4 3 2 1
Sample Output
1 2 3 4 5 6 7 8 9
答案:
/*
copy code of selection_sort() to here!
*/
void selection_sort(int a[], int len)
{
int flag = 0;
for(int i = 1; i < len; i++)
{
if(flag == 1)
return;
flag = 1;
for(int j = 0; j < len - i; j++)
{
int temp;
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
flag = 0;
}
}
}
}