1. 程式人生 > >python(三)6種排序演算法效能比較(冒泡、選擇、插入、希爾、快速、歸併)

python(三)6種排序演算法效能比較(冒泡、選擇、插入、希爾、快速、歸併)

# coding:utf-8

import random
import time

def bubble_sort(alist):
    """冒泡"""
    n = len(alist)
    for j in range(n-1):
        count = 0
        for i in range(0, n-1-j):
            if alist[i] > alist[i+1]:
                alist[i],alist[i+1] = alist[i+1], alist[i]
                count += 1
        if 0 == count:
            return

def select_sort(alist):
    """選擇"""
    n = len(alist)
    for j in range(n-1):
        min_index = j
        for i in range(j+1, n):
            if alist[min_index] > alist[i]:
                min_index = i
        alist[j], alist[min_index] = alist[min_index], alist[j]

def insert_sort(alist):
    """插入"""
    n = len(alist)
    for j in range(1, n):
        i = j
        while i > 0:
            if alist[i] < alist[i-1]:
                alist[i], alist[i-1] = alist[i-1], alist[i]
                i -= 1
            else:
                break

def shell_sort(alist):
    """希爾"""
    n = len(alist)
    gap = n // 2
    while gap > 0:
        for j in range(gap, n):
            i = j
            while i > 0:
                if alist[i] < alist[i-gap]:
                    alist[i], alist[i-gap] = alist[i-gap], alist[i]
                    i -= gap
                else:
                    break
        gap //= 2

def quick_sort(alist, first, last):
    """快速"""
    if first >= last:
        return
    mid_value = alist[first]
    low = first
    high = last
    while low < high:
        while low < high and alist[high] >= mid_value:
            high -= 1
        alist[low] = alist[high]
        while low <high and alist[low] < mid_value:
            low += 1
        alist[high] = alist[low]
    alist[low] = mid_value
    quick_sort(alist, first, low-1)
    quick_sort(alist, low+1, last)

def merge_sort(alist):
    """歸併"""
    n = len(alist)
    if n <= 1:
        return alist
    mid = n//2
    left_li = merge_sort(alist[:mid])
    right_li = merge_sort(alist[mid:])
    left_pointer, right_pointer = 0, 0
    result = []
    while left_pointer < len(left_li) and right_pointer < len(right_li):
        if left_li[left_pointer] <=  right_li[right_pointer]:
            result.append(left_li[left_pointer])
            left_pointer += 1
        else:
            result.append(right_li[right_pointer])
            right_pointer += 1
    result += left_li[left_pointer:]
    result += right_li[right_pointer:]
    return result

if __name__ == "__main__":
    seq = list(range(1, 10000))
    li = random.sample(seq, 1000)
    print(li)
    start = time.clock()
    # bubble_sort(li)# 0.118379
    # select_sort(li)# 0.049213
    # insert_sort(li)# 0.097392
    # shell_sort(li)# 0.011831
    quick_sort(li, 0, len(li) - 1)# 0.003824
    # li = merge_sort(li)# 0.005906
    end = time.clock()
    print("time: %f " % (end - start))
    print(li)

作者用一萬以內的1000個數字進行排序,快排勝出