经典排序算法的Python实现

1. 冒泡排序

  • 时间复杂度:O(n^2),相等元素的相对排序不会改变(稳定)
  • Python实现如下
def bubble_sort(xs):
    for i in range(len(xs) - 1):
        for j in range(len(xs) - 1 - i):
            if xs[j] > xs[j + 1]:
                temp = xs[j]
                xs[j] = xs[j + 1]
                xs[j + 1] = temp

2. 选择排序

  • 时间复杂度:O(n^2),相等元素的相对排序可能发生改变(不稳定)
  • Python实现如下
def selection_sort(xs):
    for i in range(len(xs) - 1):
        min_idx = i
        for j in range(i + 1, len(xs)):
            if xs[min_idx] > xs[j]:
                min_idx = j
        if min_idx != i:
            temp = xs[i]
            xs[i] = xs[min_idx]
            xs[min_idx] = temp

3. 插入排序

  • 时间复杂度:O(n^2),相等元素的相对排序不会改变(稳定)
  • Python实现如下
def insertion_sort(xs):
    for i in range(1, len(xs)):
        idx = i
        val = xs[i]
        while idx > 0 and xs[idx - 1] > val:
            xs[idx] = xs[idx - 1]
            idx -= 1
        xs[idx] = val

4. 归并排序

  • 时间复杂度:O(n*log(n)),相等元素的相对排序不会改变(稳定)
  • Python实现如下
def merge_sort(xs):
    def _merge_sort(xs, left, right):
        if left == right:
            return [xs[left]]
        mid = (left + right) // 2
        ys1 = _merge_sort(xs, left, mid)
        ys2 = _merge_sort(xs, mid + 1, right)
        p1 = 0
        p2 = 0
        temp = []
        while p1 < len(ys1) or p2 < len(ys2):
            if p1 < len(ys1) and p2 < len(ys2):
                if ys1[p1] <= ys2[p2]:
                    temp.append(ys1[p1])
                    p1 += 1
                else:
                    temp.append(ys2[p2])
                    p2 += 1
            elif p1 < len(ys1):
                temp.append(ys1[p1])
                p1 += 1
            else:
                temp.append(ys2[p2])
                p2 += 1
        return temp
    if len(xs) <= 0:
        return
    ys = _merge_sort(xs, 0, len(xs) - 1)
    for i in range(len(xs)):
        xs[i] = ys[i]

5. 快速排序

  • 时间复杂度:O(n*log(n)),相等元素的相对排序可能发生改变(不稳定)
  • Python实现如下
def quick_sort(xs):
    def _quick_sort(xs, low, high):
        if low >= high:
            return
        start = low
        end = high
        val = xs[start]
        while start < end:
            while start < end and xs[end] >= val:
                end -= 1
            xs[start] = xs[end]
            while start < end and xs[start] <= val:
                start += 1
            xs[end] = xs[start]
        pivot = start
        xs[pivot] = val
        _quick_sort(xs, low, pivot - 1)
        _quick_sort(xs, pivot + 1, high)
    _quick_sort(xs, 0, len(xs) - 1)

6. 堆排序

  • 时间复杂度:O(n*log(n)),相等元素的相对排序可能发生改变(不稳定)
  • Python实现如下
def heap_sort(xs):
    def _adjust_heap(xs, i, last):
        left = 2 * i + 1  # left child's index
        while left <= last:
            right = left + 1  # right child's index
            j = right if right <= last and xs[left] < xs[right] else left
            if xs[i] < xs[j]:
                xs[i], xs[j] = xs[j], xs[i]
                i = j
                left = 2 * i + 1  # left child's index
            else:
                break
    last = len(xs) - 1
    idx = (last - 1) // 2  # parent's index
    while idx >= 0:
        _adjust_heap(xs, idx, last)  # initialize the heap, where the root node (the first one) is the largest value
        idx -= 1
    while last >= 0:
        xs[0], xs[last] = xs[last], xs[0]  # put the largest value of the heap (the first one) to the end
        last -= 1
        _adjust_heap(xs, 0, last)  # readjust the heap

附:各排序算法的耗时测试

  • Python测试代码如下
import numpy as np
import time


if __name__ == '__main__':
    num = 10000
    xs = np.random.randint(0, num, (num,))
    np.set_printoptions(threshold=10)  # display 10 elements at most
    print('original data:\n', xs)

    ys = xs.copy()
    t0 = time.time()
    bubble_sort(ys)
    t1 = time.time()
    print('bubble sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 13.049322s

    ys = xs.copy()
    t0 = time.time()
    selection_sort(ys)
    t1 = time.time()
    print('selection sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 6.380786s

    ys = xs.copy()
    t0 = time.time()
    insertion_sort(ys)
    t1 = time.time()
    print('insertion sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 6.021922s

    ys = xs.copy()
    t0 = time.time()
    merge_sort(ys)
    t1 = time.time()
    print('merge sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 0.046878s

    ys = xs.copy()
    t0 = time.time()
    quick_sort(ys)
    t1 = time.time()
    print('quick sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 0.031252s

    ys = xs.copy()
    t0 = time.time()
    heap_sort(ys)
    t1 = time.time()
    print('heap sort:\n', ys, '(%.6fs)' % (t1 - t0))  # 0.072016s
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值