def quick_sort(arr): if len(arr) <= 1: return arr else: # 选取基准值pivot pivot = arr[0] # 将小于基准值的数放在左侧,大于基准值的数放在右侧 left = [i for i in arr[1:] if i <= pivot] right = [i for i in arr[1:] if i > pivot] # 递归排序左侧和右侧 return quick_sort(left) + [pivot] + quick_sort(right)

测试

arr = [3, 7, 1, 6, 8, 2, 5, 4] print(quick_sort(arr)) # [1, 2, 3, 4, 5, 6, 7, 8]

Python 快速排序算法实现详解

原文地址: https://www.cveoy.top/t/topic/ok6A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录