冒泡排序是排序算法中较为简单的一种,英文称为Bubble Sort。
它遍历所有的数据,每次对相邻元素进行两两比较,如果顺序和预先规定的顺序不一致,则进行位置交换;这样一次遍历会将最大或最小的数据上浮到顶端,之后再重复同样的操作,直到所有的数据有序。
如果有n个数据,那么需要的比较次数,所以当数据量很大时,冒泡算法的效率并不高。
当输入的数据是反序时,花的时间最长,当输入的数据是正序时,时间最短。
平均时间复杂度:
空间复杂度:O(1)
-
#include "stdio.h"
-
-
void swap(int *t1, int *t2)
-
{
-
int temp;
-
temp = *t1;
-
*t1 = *t2;
-
*t2 = temp;
-
}
-
-
void bubble_sort(int arr[], int len)
-
{
-
int i, j;
-
-
for (i =
0; i < len
-1; i++) {
-
for (j =
0; j < len
-1 -i; j++) {
-
if (arr[j] > arr[j +
1]) {
-
swap(&arr[j], &arr[j +
1]);
-
}
-
}
-
}
-
}
-
-
-
int main()
-
{
-
int arr[] = {
34,
27,
55,
8,
97,
67,
35,
43,
22,
101,
78,
96,
35,
99};
-
int i;
-
int len =
sizeof(arr) /
sizeof(*arr);
-
-
bubble_sort(arr, len);
-
printf(
"len = %d \n", len);
-
printf(
"use bubble sort the arrary is: ");
-
-
for(i =
0; i < len; i++){
-
printf(
"%d ", arr[i]);
-
}
-
printf(
"\n");
-
}
-