标签:快速 shuf return 情况 pat color pre bsp .sh
快速排序,尾递归。最坏情况下栈深度Θ(lgn)
1 import random 2 def patition(A, l, r): 3 j = l 4 key = A[r] 5 for i in range(l, r+1): 6 if A[i] < key: 7 temp = A[j] 8 A[j] = A[i] 9 A[i] = temp 10 j += 1 11 A[r] = A[j] 12 A[j] = key 13 return j 14 15 def quicksort(A, l, r): 16 if l < r: 17 p = patition(A, l, r) 18 recusive_tail_quicksort(A, l, p-1) 19 recusive_tail_quicksort(A, p+1, r) 20 21 def recusive_tail_quicksort(A, l, r): 22 while l < r: 23 p = patition(A, l, r) 24 if (p-l) <= (r-p): 25 recusive_tail_quicksort(A, l, p-1) 26 l = p + 1 27 else: 28 recusive_tail_quicksort(A, p+1, r) 29 r = p-1 30 31 list1 = [i for i in range(100)] 32 random.shuffle(list1) 33 print(list1) 34 recusive_tail_quicksort(list1, 0, len(list1)-1) 35 print(list1)
标签:快速 shuf return 情况 pat color pre bsp .sh
原文地址:http://www.cnblogs.com/MrWrong/p/7110240.html