Python算法-排序

1. 冒泡排序

def bubble_sort(seq):
    n = len(seq)
    for i in range(n-1):
        for j in range(n-1-i): # compare with the left
            if seq[j]>seq[j+1]:
                seq[j],seq[j+1] = seq[j+1],seq[j] #exchange

a = [2,4,1,5,3]
assert sorted(a) ==bubble_sort(a)

https://goo.gl/DttdU6

2. 选择排序

def select_sort(seq):
    n = len(seq)
    for i in range(n-1):
        min_idx = i
        for j in range(i+1,n):
            if seq[j]<seq[min_idx]:
                min_idx = j
        if min_idx != i:
            seq[i],seq[min_idx] = seq[min_idx],seq[i]

a = [2,4,1,5,3]
select_sort(a)

https://goo.gl/tFFfME

3. 插入排序

def insertion_sort(seq):
    n = len(seq)
    print(seq)
    for i in range(1,n):
        value = seq[i]
        pos = i
        while pos>0 and value<seq[pos-1]:
            seq[pos] = seq[pos-1]
            pos -= 1
        seq[pos]=value
        print(seq)

a = [2,4,1,5,3]
insertion_sort(a)

https://goo.gl/vcxPbd

4. 快速排序(简单粗暴版)

def quick_sort(seq):
    if len(seq) <= 1:
        return seq
    else:
        pivot_index = 0
        pivot = seq[pivot_index]
        less_part = [x for x in seq[pivot_index+1:] if x <= pivot]
        large_part = [x for x in seq[pivot_index+1:] if x > pivot]
        return quick_sort(less_part) + [pivot] + quick_sort(large_part)

a = [2,4,1,5,3]
quick_sort_a = quick_sort(a)
assert quick_sort_a == sorted(a)

https://goo.gl/pD8wEM

5. 快速排序(内存,效率优化版)

def partition(seq, begin, end):
    pivot_index = begin
    pivot = seq[pivot_index]
    l,r = pivot_index + 1, end - 1

    while True:
        while l <= r and seq[l] < pivot:
            l += 1
        while r >= l and seq[r] >= pivot:
            r -= 1
        if l > r:
            break
        else:
            seq[l],seq[r]=seq[r],seq[l]

    seq[pivot_index],seq[r] = seq[r], seq[pivot_index]
    return r

def quick_sorted_inplace(array, begin, end):
    if begin < end:
        pivot = partition(array, begin, end)
        quick_sorted_inplace(array, begin, pivot)
        quick_sorted_inplace(array, pivot+1, end)

a = [2,4,1,5,3]
quick_sorted_inplace(a,0,len(a))

https://goo.gl/JQh5A1

posted @ 2018-08-07 09:35  Siucaan  阅读(146)  评论(0编辑  收藏  举报