学习之后,自己练习手写一下排序算法,加深印象
原理:顾名思义,此种算法排序的数字像气泡一样,一个个往上浮。两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止
#define MAXSIZE 10
#include <stdio.h>
struct a{
int array[MAXSIZE];
int length;
};
void init_array(struct a *L){
int i;
L->length = MAXSIZE;
for (i=1;i<L->length;i++){
scanf("%d",&(L->array[i]));
}
}
void swap(struct a *L,int i,int j){
int temp = L->array[i];
L->array[i] = L->array[j];
L->array[j] = temp;
}
void print(struct a *L){
int i;
for (i=1;i<L->length;i++){
printf("%d ",L->array[i]);
}
}
void bubbleSort(struct a *L){
int i;
int j;
for (i=1;i<L->length;i++){
for (j=L->length-1;j>1;j--){
if (L->array[j-1]>L->array[j]){
swap(L,j-1,j);
}
}
}
}
int main(){
struct a List;
init_array(&List);
printf("排序前:");
print(&List);
bubbleSort(&List);
printf("\n排序后:");
print(&List);
return 0;
}
算法时间复杂度:O(n2)