排序算法-Python

冒泡 bubble_sort

def bubble_sort(li):  # 这个其实是选择排序
    for i in range(len(li) - 1):  # 趟数
        max_id = 0  # 本趟最大值下标
        exchange = False
        for j in range(1, len(li) - i):  # 无序区间
            if li[max_id] < li[j]:
                max_id = j
            else:
                exchange = True
        if not exchange:
            break
        li[max_id], li[len(li)-1-i] = li[len(li)-1-i], li[max_id]

选择 select_sort

def select_sort(li):
    for i in range(len(li)-1):  # 趟数
        min_idx = i
        for j in range(i+1, len(li)):
            if li[min_idx] > li[j]:
                min_idx = j
        li[min_idx], li[i] = li[i], li[min_idx]

插入 insert_sort

def insert_sort(li):
    for i in range(1, len(li)):  # 摸的第i手牌
        j = i - 1
        tmp = li[i]
        while j >= 0 and tmp < li[j]:  # 有序区
            li[j+1] = li[j]
            j -= 1
        li[j+1] = tmp

快排 quick_sort

# 给定元素P(默认子列表的第0个元素),给P归位,返回P的下标
def partition1(li, left, right):
    # 先从右边开始比较
    while left < right:
        while left < right and li[right] >= li[left]:
            right -= 1
        li[right], li[left] = li[left], li[right]
        while left < right and li[left] < li[right]:
            left += 1
        li[left], li[right] = li[right], li[left]
    return left


def partition(li, left, right):
    # 这个理解起来更简单
    tmp = li[left]
    while left < right:
        while left < right and li[right] >= tmp:
            right -= 1
        li[left] = li[right]
        while left < right and li[left] < tmp:
            left += 1
        li[right] = li[left]
    li[left] = tmp
    return left


def _quick_sort(li, left, right):
    if left >= right:
        return
    mid = partition(li, left, right)
    _quick_sort(li, left, mid-1)
    _quick_sort(li, mid+1, right)


@cal_time
def quick_sort(li):
    _quick_sort(li, 0, len(li)-1)

堆排 heap_sort

def sift(li, low, high):
    new_item = li[low]  # 代表要调整的数
    i = low  # 指向空出来的位置
    j = i * 2 + 1  # 初始指向左子节点
    while j <= high:
        if j < high and li[j] < li[j+1]:
            j = j + 1
        if new_item < li[j]:
            li[i] = li[j]
            i = j
            j = i * 2 + 1
        else:
            break
    li[i] = new_item


@cal_time
def heap_sort(li):
    """堆排序"""
    n = len(li)
    # 构建大根堆
    for root in range((n-2) // 2, -1, -1):
        sift(li, root, n-1)
    # 出数
    for i in range(n-1, 0, -1):
        li[0], li[i] = li[i], li[0]
        sift(li, 0, i-1)

计时

def cal_time(func):
    def inner(*args, **kwargs):
        start = datetime.now().timestamp() * 1000
        func(*args, **kwargs)
        spend = datetime.now().timestamp() * 1000 - start
        if spend > 9999:
            spend_str = '%ds' % (spend/1000)
        else:
            spend_str = '%dms' % spend
        print('it spends %s' % spend_str)
    return inner

你可能感兴趣的:(python,算法,排序算法,python,算法)