Bubble Sort

冒泡算法, 一种简单的排序算法

复杂度: 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$

参考: Wikipedia Bubble sort

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值