编写冒泡排序函数,函数原型:void bubblesort(int a[],int n);对n个整数升序排序。
编写选择排序函数,函数原型:void selectsort(int a[],int n);对n个整数降序排序。
编写main函数,输入10个整数,利用函数将其按升序和降序分别输出排序结果。(输入输出数据间用一个空格分隔)
测试样例:
如输入:
5 2 8 9 10 1 3 4 7 6
则输出为:
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
#include<stdio.h>
//冒泡排序升序
void bubblesort(int a[], int n)
{
for (int i=0; i < n - 1; i++)
for (int j=0; j < n-1 - i; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
for (int i = 0; i < n-1; i++)
{
printf("%d ", a[i]);
}
printf("%d", a[n-1]);
}
//选择排序降序
void selectsort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int temp = i;
for (int j = i + 1; j < n; j++)
{
if (a[temp] < a[j]) //查找剩余部分最大值
{
temp = j;
}
}
if (temp != i)
{
int m = a[i];
a[i] = a[temp];
a[temp] = m;
}
}
for (int i = 0; i < n-1; i++)
{
printf("%d ", a[i]);
}
printf("%d", a[n-1]);
}
int main()
{
int n, a[10] = { 5, 2, 8, 9 ,10, 1, 3, 4 ,7 ,6 };
n = 10;
for (int i = 0; i < 10; i++)
{
scanf_s("%d ", &a[i]);
}
bubblesort(a, 10);
printf("\n");
selectsort(a, 10);
return 0;
}