以下是Python实现快速排序的代码,同时对(7,1,4,8)进行了排序:

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

arr = [7, 1, 4, 8]
sorted_arr = quick_sort(arr)
print(sorted_arr)

输出结果为:[1, 4, 7, 8]

用python写一段快速排序并用7148举例实现

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

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