本文主要介紹用python實現基本的快速排序算法,體會一下python的快排代碼可以寫得多麼簡潔。
1. 三言兩語概括算法核心思想
先從待排序的數組中找出一個數作爲基準數(取第一個數即可),然後將原來的數組劃分成兩部分:小於基準數的左子數組和大於等於基準數的右子數組。然後對這兩個子數組再遞歸重複上述過程,直到兩個子數組的所有數都分別有序。最後返回“左子數組” + “基準數” + “右子數組”,即是最終排序好的數組。
2. Talk is cheap, show the code
# 實現快排
def quicksort(nums):
if len(nums) <= 1:
return nums
# 左子數組
less = []
# 右子數組
greater = []
# 基準數
base = nums.pop()
# 對原數組進行劃分
for x in nums:
if x < base:
less.append(x)
else:
greater.append(x)
# 遞歸調用
return quicksort(less) + [base] + quicksort(greater)
def main():
nums = [6,1,2,7,9,3,4,5,10,8]
print quicksort(nums)
main()
輸出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]