常用排序算法(Python)

冒泡排序:

核心思想:遍历长度为n的数组,每轮序号为i,第i轮将最值移动到数组倒数n-i的位置,第i轮中,内层循环到第n-i个值为止
也就是说,每轮循环中将这一轮中最值移动到数组尾部,下一轮循环时与已经移动到尾部的值无关

def bubble_sort(l):
    assert isinstance(l, list)
    size = len(l)
    if size <= 1:
        return l

    for i in range(size):
        for j in range(size - i - 1):
            if l[j] < l[j + 1]:
                l[j], l[j + 1] = l[j + 1], l[j]
    return l


if __name__ == '__main__':
    arr = [5, 2, 6, 3]
    print(bubble_sort(arr))


插入排序:

核心思想:按顺序遍历数组,每次将取出的值和新数组中已有值进行比较,有以下几种情况:
1:比ret中的最大值大,插入最前面;2:介于ret中某两个数中间,插入这两个数中间;3:1,2两种情况之外,追加到数组最后

def insert_sort(l):
    assert isinstance(l, list)
    size = len(l)
    if size <= 1:
        return l
    ret = []

    for i in range(size):
        for j in range(len(ret)):
            if l[i] >= ret[j] and (j == 0 or l[i] < ret[j - 1]):
                ret.insert(j, l[i])
                break
        else:
            ret.append(l[i])

    return ret


if __name__ == '__main__':
    arr = [5, 2, 6, 3, 1, 2]
    print(insert_sort(arr))

选择排序:

核心思想:

for i in len(list),每次找到从位置i开始到末尾中最值的index,将i与index对应的值进行交换

def select_sort(l):
    assert isinstance(l, list)
    size = len(l)
    if size <= 1:
        return l

    def _max(start):
        max_index = start
        for i in range(start, size):
            if l[max_index] < l[i]:
                max_index = i
        return max_index

    for i in range(size):
        index = _max(i)
        if i != index:
            l[index], l[i] = l[i], l[index]

    return l


if __name__ == '__main__':
    arr = [5, 2, 6, 3, 8, 2]
    print(select_sort(arr))

合并排序:

核心思想:每次把数组从中间截断为两个数组,对这两个数组分别进行递归调用合并排序,然后将排序后的两个数组合并为最终结果
def merge_sort(l):
    assert isinstance(l, list)
    size = len(l)
    if size <= 1:
        return l
    if size == 2:
        if l[0] < l[1]:
            l[0], l[1] = l[1], l[0]
        return l
    else:
        ret = []
        mid_index = size // 2
        l_a = merge_sort(l[0:mid_index])
        l_b = merge_sort(l[mid_index:size])
        i = 0
        j = 0
        while len(ret) < size:
            if i >= len(l_a):
                ret.extend(l_b[j:])
                break
            if j >= len(l_b):
                ret.extend(l_a[i:])
                break
            if l_a[i] > l_b[j]:
                ret.append(l_a[i])
                i += 1
            else:
                ret.append(l_b[j])
                j += 1
        return ret


if __name__ == '__main__':
    arr = [5, 2, 6, 3, 1, 2]
    print(merge_sort(arr))

快速排序:

核心思想:任取一值,将其分为大于等于该值的数组和小于该值的数组,对分离出的两个数组再进行排序,得到两个排序好的数组,然后将所得的两个数组,和中间值拼接成一个数组
def quick_sort(l):
    assert isinstance(l, list)
    if len(l) <= 1:
        return l
    l_gt = [x for x in l[1:] if x >= l[0]]
    l_lt = [x for x in l[1:] if x < l[0]]
    return quick_sort(l_gt) + [l[0]] + quick_sort(l_lt)


if __name__ == '__main__':
    arr = [5, 2, 6, 3, 8, 2]
    print(quick_sort(arr))




此外,还有堆排序,二叉树排序,木桶排序等,留待以后补充

你可能感兴趣的:(Python)