标签:
快速排序
第一种写法,效率很低
1 def quickSort(array, low, high): 2 if low >= high: 3 return 4 i, j = low, high 5 tmp = array[low] 6 while True: 7 while array[j] > tmp and i < j: 8 j -= 1 9 if i < j: 10 array[i] = array[j] 11 i += 1 12 while array[j] < tmp and i < j: 13 i += 1 14 if i < j: 15 array[j] = array[i] 16 j -= 1 17 else: 18 break 19 array[i] = tmp 20 quickSort(array, low, i - 1) 21 quickSort(array, j + 1, high)
第二种写法,体现python的优点,很简洁,速度也快
1 def quickSort(L): 2 if len(L) <= 1: 3 return L 4 pivot = L[0] 5 lessor = quickSort([x for x in L[1:] if x < pivot]) 6 larger = quickSort([x for x in L[1:] if x >= pivot]) 7 return lessor + [pivot] + larger
当然,这样简单的排序,和python内置的排序算法相比,效率会差得多
标签:
原文地址:http://www.cnblogs.com/aeropig/p/quick_sort.html