Posted on 2017-09-29 23:04
路缘 阅读(1613)
评论(0) 编辑 收藏 引用 所属分类:
C/C++
老程序员了,还来写基础算法。本人过去多年主要做C++服务端开发,最近找工作新学python,写个快速排序练练手。
1
2 import numpy as np
3 def sub_sort(array,low,high):
4 data_value = array[low]
5 origLow = low
6 origHigh = high
7 while low < high:
8 while low < high and array[high] >= data_value:
9 high -= 1
10 while low < high and array[high] < data_value:
11 array[low] = array[high]
12 low += 1
13 array[high] = array[low]
14 array[low] = data_value
15 return low
16
17
18 def quick_sort(array,low,high):
19 if low < high:
20 key_index = sub_sort(array,low,high)
21 quick_sort(array,low,key_index)
22 quick_sort(array,key_index+1,high)
23
24
25 if __name__ == '__main__':
26 array = np.arange(30)
27 np.random.shuffle(array)
28 print(array)
29 quick_sort(array,0,len(array)-1)
30 print("quick sort:", array)
31
运行结果:
================= RESTART: D:\work\test\python\quick_sort.py =================
[ 2 19 7 15 4 11 12 17 20 1 3 18 27 8 14 0 16 22 21 13 10 6 28 29 26
23 24 5 25 9]
quick sort: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29]