快速排序和归并排序的非递归实现

1.快速排序

# 快速排序
def partition(li, left, right):
    i = left
    j = right
    r = random.randint(i, j)
    li[i], li[r] = li[r], li[i]
    tmp = li[i]
    while i < j:
        while i < j and li[j] >= tmp:
            j -= 1
        li[i] = li[j]
        while i < j and li[i] <= tmp:
            i += 1
        li[j] = li[i]
    li[i] = tmp
    return i


def quick_sort(li, left, right):
    l = [left, right]
    while len(l) > 0:
        i = l.pop(0)
        j = l.pop(0)
        if i < j:
            k = partition(li, i, j)
            l.extend([i, k - 1, k + 1, j])

 

2.归并排序

def merge(li, left, mid, right):
    i = left
    j = mid + 1
    tmp = []
    while i <= mid and j <= right:
        if li[i] <= li[j]:
            tmp.append(li[i])
            i += 1
        else:
            tmp.append(li[j])
            j += 1
    tmp.extend(li[i:mid + 1]) if i <= mid else tmp.extend(li[j:right + 1])
    li[left:right + 1] = tmp

def merge_sort(li):
    l = len(li)
    s = 1
    while s < l:
        left = 0
        while left + s < l:
            mid = left + s - 1
            right = mid + s
            if right > l - 1:
                right = l - 1
            merge(li, left, mid, right)
            left = right + 1
        s *= 2

 

posted @ 2018-10-18 21:13  Coufusion  阅读(186)  评论(0编辑  收藏  举报