Python bubble sort selection sort insertion sort quick sort merge sort algorithm source code

Without further ado, go directly to the source code

def bubble_sort(arr):
    """冒泡排序  stable

    :param arr: List[T]
    :return: List[T]
    """
    arr = arr.copy()
    for i in reversed(range(1, len(arr))):
        # 最大的往后扔
        for j in range(i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr


def select_sort(arr):
    """选择排序  stable

    :param arr: List[T]
    :return: List[T]
    """
    arr = arr.copy()
    for i in range(len(arr) - 1):
        # 获取idx在前的最小值
        min_idx = i  # 基准值
        for j in range(i + 1, len(arr)):
            if arr[min_idx] > arr[j]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr


def insert_sort(arr):
    """插入排序  stable

    :param arr: List[T]
    :return: List[T]
    """
    arr = arr.copy()
    out = []
    for val in arr:
        for i in range(len(out)):
            if val <= out[i]:
                out.insert(i, val)
                break
        else:
            out.append(val)
    return out


def quick_sort(arr):
    """快速排序  非stable

    :param arr: List[T]
    :return: List[T]
    """
    arr = arr.copy()

    def div_group(arr, start, end):
        """分组, 以arr[start]的大小为标准,小于的放左边, 大于的放右边.(arr被直接修改). [start, end)

        :param arr: List[T]
        :return: mid: arr[start] 最后的位置(已计算了start). mid不是中间的位置
        """
        value = arr[start]  # 取第一个为标准
        low, high = start, end - 1
        while low < high:
            while low < high:
                if arr[high] < value:
                    arr[low] = arr[high]
                    break
                high -= 1
            while low < high:
                if arr[low] > value:
                    arr[high] = arr[low]
                    break
                low += 1
        # 跳出循环时: low == high
        arr[low] = value
        return low

    def _quick_sort(arr, start, end):
        """快速排序  非stable  (arr被直接修改)  [start, end)"""
        if end - start <= 1:  # <= 1个元素时
            return
        mid = div_group(arr, start, end)
        _quick_sort(arr, start, mid)
        _quick_sort(arr, mid + 1, end)

    _quick_sort(arr, 0, len(arr))
    return arr


def merge_sort(arr):
    """归并排序  stable

    :param arr: List[T]
    :return: List[T]
    """
    arr = arr.copy()

    def merge(arr, start, mid, end):
        """mid: 不是中间点的意思, 而是两个有序列表的分割点[start, mid), [mid, end).
        虽然在该merge_sort()中, mid 就是中心点  (arr被直接修改)"""
        front = arr[start: mid].copy()  # 前半部分备份
        i, j = start, mid
        idx = start  # 复写的下标
        while idx < end:
            if j >= end or i < mid and front[i - start] < arr[j]:  # not (j < end)
                # back下标溢出就直接进行
                arr[idx] = front[i - start]
                i += 1
            else:
                arr[idx] = arr[j]
                j += 1
            idx += 1

    def _merge_sort(arr, start, end):
        """归并排序  stable  (arr被直接修改)  [start, end)"""
        if end - start <= 1:  # <= 1个元素时
            return
        mid = (start + end) // 2
        _merge_sort(arr, start, mid)
        _merge_sort(arr, mid, end)
        merge(arr, start, mid, end)

    _merge_sort(arr, 0, len(arr))
    return arr


import random
from tools import get_runtime
arr = list(range(10))
random.seed(0)
random.shuffle(arr)

print(bubble_sort(arr))
print(select_sort(arr))
print(insert_sort(arr))
print(quick_sort(arr))
print(merge_sort(arr))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

arr = list(range(10000))
random.seed(0)
random.shuffle(arr)


def get_runtime(func, *args, **kwargs):
    t = time.time()
    result = func(*args, **kwargs)
    print(time.time() - t)
    return result


get_runtime(bubble_sort, arr)
get_runtime(select_sort, arr)
get_runtime(insert_sort, arr)
get_runtime(quick_sort, arr)
get_runtime(merge_sort, arr)
get_runtime(sorted, arr)
# 7.944378852844238
# 2.72172212600708
# 1.0584454536437988
# 0.02190852165222168
# 0.03390908241271973
# 0.0019948482513427734

Published 9 original articles · Likes2 · Visits 559

Guess you like

Origin blog.csdn.net/qq_40939814/article/details/105445057