交换排序是交换元素的位置。
本文针对交换排序中的冒泡排序。
第一次冒泡将n个数据中的最大的数据放到最后一个位置,第二次冒泡将前n-1个数据中的最大的数据放到倒数第二个位置……
因此需要比较1+2+……+(n-1)次,时间复杂度是O(n的平方)。
程序:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
#define N 15
typedef struct{
int key;
int other;
}node;
typedef struct
{
node array[MAXSIZE];
int length;
}list;
//冒泡排序
void bubble_sort(list *l,int n)
{
int i,j,ok;
node temp;
for(i = n - 1,ok = 1;i > 1 && ok;--i){ //ok可以少做没必要的比较,即未排序的已经有序了就不用再比较了
ok = 0;
for(j = 0;j < i;++j)
if(l->array[j].key > l->array[j + 1].key){
temp = l->array[j];
l->array[j] = l->array[j + 1];
l->array[j + 1] = temp;
ok = 1;
}
}
}
void print(list *l)
{
int i;
for(i = 1;i < l->length;i++)
printf("%d %d\t",l->array[i].key,l->array[i].other);
printf("\n");
}
void main()
{
node data[N]={{5,6},{13,5},{22,2},{2,4},{6,5},{99,7},{6,15},{1,22},{15,12},{58,12},{48,40},{26,48},{38,35},{72,58},{61,22}};
list l;
int i;
for(i = 0;i < N;i++)
l.array[i] = data[i];
l.length = N;
printf("befor sort:\n");
print(&l);
bubble_sort(&l,N);
printf("after bubble sort:\n");
print(&l);
}
结果:
[11:00:59]# ./c
befor sort:
13 5 22 2 2 4 6 5 99 7 6 15 1 22 15 12 58 12 48 40 26 48 38 35 72 58 61 22
after bubble sort:
2 4 5 6 6 5 6 15 13 5 15 12 22 2 26 48 38 35 48 40 58 12 61 22 72 58 99 7
2万+

被折叠的 条评论
为什么被折叠?



