【问题描述】
实现冒泡排序、简单选择排序、直接插入排序。
【输入形式】
输入3组待排序序列。
【输出形式】
输出分别使用冒泡、选择、插入排序的每趟排序结果。
【样例输入】
5
7 3 5 0 -9
3
9 8 0
6
2 4 6 3 4 2
【样例输出】
insertSort:
3 7 5 0 -9
3 5 7 0 -9
0 3 5 7 -9
-9 0 3 5 7
selectSort:
0 8 9
0 8 9
bubbleSort:
2 4 3 4 2 6
2 3 4 2 4 6
2 3 2 4 4 6
2 2 3 4 4 6
【样例说明】
从样例可以看出,直接插入排序和选择排序排序趟数都是n-1,而冒泡排序是改进后的排序算法,排序趟数<=n-1。
每趟排序完成,调用printList输出当前结果。
注意:选择排序,每趟选择只做一次交换(而不是每次比较都做交换)
#include
#include
#define MAX 1000
void printList(int list[], int n)
{
int i;
for(i=0; i{
printf("%d ", list[i]);
}
printf("\n");
}
void insertSort(int list[], int n)
{
int a[1000];
int i,j,t;
for(i=0;i
a[i]=list[i];
}
for(i=1;i{
t=a[i];
j=i-1;
while(j>=0&&t{
list[j+1]=list[j];
j--;
}
list[j+1]=t;
printList(list,n);
}
}
void selectSort(int list[], int n)
{
int i,j;
int temp,pos;
for(i=0;i{
pos=i;
for(j=i+1;j{
if(list[pos]>list[j])
pos=j;
}
if(i!=pos)
{
temp=list[i];
list[i]=list[pos];
list[pos]=temp;
}
printList(list,n);
}
}
void bubbleSort(int list[], int n)
{
int i,j,t,flag=0;
for(i=0;i{
for(j=0;j{
if(list[j]>list[j+1])
{
t=list[j];
list[j]=list[j+1];
list[j+1]=t;
flag=1;
}
}
if(flag){
printList(list,n);
}
flag=0;
}
}
int main()
{
int i,n;
int a[MAX];
scanf("%d",&n);
for(i=0;i{
scanf("%d",&a[i]);
}
printf("insertSort:\n");
insertSort(a,n);
scanf("%d",&n);
for(i=0;i{
scanf("%d",&a[i]);
}
printf("selectSort:\n");
selectSort(a,n);
scanf("%d",&n);
for(i=0;i{
scanf("%d",&a[i]);
}
printf("bubbleSort:\n");
bubbleSort(a,n);
return 0;
}