1 #-*- coding: UTF-8 -*- 2 import numpy as np 3 4 def Partition(a, i, j): 5 x = a[i] #将数组的第一个元素作为初始基准位置 6 p = i #同时记录下该元素的位置 7 while i < j: 8 while i < j and a[j] >= x: 9 j -= 1 10 while i < j and a[i] <= x: 11 i += 1 12 if i != j: 13 a[i], a[j] = a[j], a[i] #交换a[i]与a[j] 14 a[p], a[i] = a[i], a[p] #将a[p]与a[i]进行交换 15 p = i #得到分隔位置 16 17 return p 18 19 def QuickSort(a, i, j): 20 if i < j: 21 p = Partition(a, i, j) 22 QuickSort(a, i, p-1) 23 QuickSort (a, p+1, j) 24 25 if __name__ == '__main__': 26 27 a = np.random.randint(0, 100, size = 100) 28 print "Before sorting..." 29 print "---------------------------------------------------------------" 30 print a 31 print "---------------------------------------------------------------" 32 QuickSort(a, 0, a.size - 1) 33 print "After sorting..." 34 print "---------------------------------------------------------------" 35 print a 36 print "---------------------------------------------------------------"