冒泡算法, 一种简单的排序算法
复杂度: O(n^2)
伪代码:
bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
C语言实现:
// utility.h
#ifndef _UTILITY_H_
#define _UTILITY_H_
#define ARR_SIZE(a) sizeof(a)/sizeof(a[0])
print_arr(int arr[], int len)
{
int i=0;
for (;i<len;i++)
printf("%d, ", arr[i]);
printf("\n");
}
#endif
#include <stdio.h>
#include "utility.h"
void BubbleSort(int arr[], int len)
{
int i=0, j=0, tmp=0;
/*int arr_len = len;*/
for (i=0; i<len; i++)
{
for (j=1; j<len; j++)
if (arr[j-1] > arr[j])
{
tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
/*print_arr(arr, arr_len);*/
len--;
}
}
int main()
{
int arr[] = {5,1,4,2,8,9,7,3,6,17,11};
int len = ARR_SIZE(arr);
BubbleSort(arr, len);
printf("bubble sort result:\n");
print_arr(arr, len);
return 0;
}
//运行结果:
dennis@dennis-VirtualBox:~/project/sort$ ./bubble
bubble sort result:
1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 17,
dennis@dennis-VirtualBox:~/project/sort$
Python实现:
#!/usr/bin/env python
import random
def bubble_sort(x, len):
for i in range(len):
swap=0
for j in range(len-1):
if (x[j]>x[j+1]):
(x[j], x[j+1]) = (x[j+1], x[j])
swap=1
if swap==0:
print 'break at len:',len
break
len = len -1
if __name__ == '__main__':
arr=[]
len = 10
for i in range(len):
arr.append(random.randint(1,100))
print 'list before sort:',arr
bubble_sort(arr, len)
print 'list after sort:',arr
##运行结果:
dennis@dennis-VirtualBox:~/project/sort$ python bubble_sort.py
list before sort: [37, 13, 7, 75, 45, 40, 58, 96, 77, 74]
break at len: 7
list after sort: [7, 13, 37, 40, 45, 58, 74, 75, 77, 96]
dennis@dennis-VirtualBox:~/project/sort$ python bubble_sort.py
list before sort: [71, 68, 88, 4, 80, 64, 50, 48, 69, 8]
break at len: 2
list after sort: [4, 8, 48, 50, 64, 68, 69, 71, 80, 88]
dennis@dennis-VirtualBox:~/project/sort$