Python实现快速排序

一、代码如下

1、快排函数

def quick_sort(array):
    if len(array) <=1:
        return array
    else:
        pivot = array[0]
        less = [i for i in array[1:] if i <= pivot]
        greater = [i for i in array[1:] if i > pivot]
        return quick_sort(less) + [pivot] + quick_sort(greater)

2、调用函数

import numpy as np

def main():
    # 初始化数组
    l = [3, 7, 1, 6, 4, 5, 8, 2]
    a = np.array(l)
 
    # 调用快排函数
    result = quick_sort(a)

    # 输出结果
    print(result)

if __name__ == "__main__":
    main()

3、原理解释

初始化 3 7 1 6 4 5 8 2
pivot 3
less 1 2
greater 7 6 4 5 8
less 1 2
pivot 1
greater 2
pivot 3
greater 7 6 4 5 8
less 6 4 5
less 4 5
pivot 4
greater 5
pivot 6
pivot 7
greater 8

你可能感兴趣的:(Python,基础知识,算法,排序算法,python)