python3 数据结构和算法(1) 排序

0.util

import random
import time
from functools import wraps

def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print('%-30s %10s %f' % (func.__name__, ' cost time:', end - start))
        return result
    return wrapper

def dump(array):
    for i in range(0, len(array)):
        print(array[i], end=', ')
    print()


def same(arr1, arr2):
    if len(arr1) != len(arr2):
        return False

    for i in range(0, len(arr1)):
        if arr1[i] != arr2[i]:
            return False
    return True

def check_sorted(array):
    s = sorted(array)
    if s != array:
        print('error')

1.插入排序(insertion sort)

def insertion_sort(array, g):
    for i in range(g, len(array)):
        v = array[i];
        j = i - g
        while j >= 0 and array[j] > v:
            array[j+g] = array[j]
            j -= g
        array[j+g] = v

@timethis
def test_insertion_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        insertion_sort(array, 1)
        check_sorted(array)

2.冒泡排序(bubble sort)

def bubble_sort(a):
    for i in range(len(a)):
        flag = False
        for j in range(len(a)-1, i, -1):
            if a[j] < a[j-1]:
                a[j], a[j-1] = a[j-1], a[j]
                flag = True

        if not flag:
            break

@timethis
def test_bubble_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        bubble_sort(array)
        check_sorted(array)

3.选择排序(selection sort)

def selection_sort(a):
    for i in range(len(a)-1):
        m = i
        for j in range(i+1, len(a)):
            if a[j] < a[m]:
                m = j
        a[i], a[m] = a[m], a[i]

@timethis
def test_selection_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        selection_sort(array)
        check_sorted(array)

4.希尔排序(shell sort)

def shell_sort(a, gn):
    for g in reversed(gn):
        insertion_sort(a, g)


@timethis
def test_shell_sort():
    n, h = 1000, 1
    gn = []
    while h <= n:
        gn.append(h)
        h = 3*h + 1

    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        shell_sort(array, gn)
        check_sorted(array)

5.归并排序(merge sort)

def merge(a, l, m, r):
    al = a[l : m+1]
    ar = a[m+1 : r+1]

    al.append(float('INF'))
    ar.append(float('INF'))

    i, j = 0, 0
    for k in range(l, r+1):
        if al[i] < ar[j]:
            a[k] = al[i]
            i += 1
        else:
            a[k] = ar[j]
            j += 1

def merge_sort(a, l, r):
    if l < r:
        m = (l + r) // 2
        merge_sort(a, l, m)
        merge_sort(a, m+1, r)
        merge(a, l, m, r)


@timethis
def test_merge_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        merge_sort(array, 0, len(array)-1)
        check_sorted(array)

6.快速排序(quick sort)

def partition(a, l, r):
    x = a[r]
    i = l - 1
    for j in range(l, r):
        if a[j] <= x:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i+1], a[r] = a[r], a[i+1]
    return i+1

def quick_sort(a, l, r):
    if l < r:
        p = partition(a, l, r)
        quick_sort(a, l, p-1)
        quick_sort(a, p+1, r)



@timethis
def test_quick_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        quick_sort(array, 0, len(array)-1)
        check_sorted(array)

7.计数排序(counting sort)

def counting_sort(a, max_val):
    count = [0] * (max_val+1)
    for v in a:
        count[v] += 1

    j = 0
    for i in range(max_val+1):
        for c in range(count[i]):
            a[j] = i
            j += 1

@timethis
def test_counting_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        counting_sort(array, 10000)
        check_sorted(array)

8.堆排序(heap sort)

def heapify(a, i, heap_size):
    l = (i+1) * 2 - 1
    r = (i+1) * 2

    largest = i
    if l < heap_size and a[l] > a[largest]:
        largest = l
    if r < heap_size and a[r] > a[largest]:
        largest = r

    if largest != i:
        a[i], a[largest] = a[largest], a[i]
        heapify(a, largest, heap_size)

def build_heap(a):
    heap_size = len(a)
    for i in range(len(a)//2, -1, -1):
        heapify(a, i, heap_size)

def heap_sort(a):
    build_heap(a)
    for i in range(len(a)-1, 0, -1):
        a[0], a[i] = a[i], a[0]
        heapify(a, 0, i)

@timethis
def test_heap_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        heap_sort(array)
        check_sorted(array)
@timethis
def test_buildin_sort():
    for i in range(10):
        array = [ random.randint(1, 10000) for i in range(1000) ]
        array = sorted(array)


def test_sort():
    test_buildin_sort()
    test_insertion_sort()
    test_bubble_sort()
    test_selection_sort()
    test_shell_sort()
    test_merge_sort()
    test_quick_sort()
    test_counting_sort()
    test_heap_sort()

def main():
    test_sort()

if __name__ == '__main__':
    main()

test_buildin_sort cost time: 0.013457
test_insertion_sort cost time: 0.278185
test_bubble_sort cost time: 0.633724
test_selection_sort cost time: 0.274748
test_shell_sort cost time: 0.030936
test_merge_sort cost time: 0.036765
test_quick_sort cost time: 0.026572
test_counting_sort cost time: 0.032006
test_heap_sort cost time: 0.049690

猜你喜欢

转载自blog.csdn.net/guzhou_diaoke/article/details/81415331