重庆分公司
重庆分公司
python快速排序实现
-
import random
-
-
num_list = []
-
for x in range(30):
-
num_list.append(random.randint(1, 500))
-
-
list_len = len(num_list)
-
print(list_len)
-
-
-
def quick_sort(array, begin, end):
-
# (1) 104, 17, 510,30,100 这是用来说明的例子,请按前面的序号阅读
-
# i j
-
if begin < end:
-
i, j = begin, end
-
# 设置临时基准
-
temp = array[i]
-
# --------------------------------------------
-
while i < j:
-
# 如果列表后边的数,比基准数大或相等,j则前移一位,直到出现第一个比基准数小的数
-
while (i < j) and (array[j] >= temp):
-
j = j - 1
-
# 找到后把第j个元素赋值给第i个元素
-
array[i] = array[j] # (2)100,17,510,30,100 (4)100, 17, 30, 30, 510
-
# i j i j <-- j
-
# 若前边的数比基准数小或相等,i则后移一位,直到出现第一个比基准数大的数
-
while (i < j) and (array[i] <= temp):
-
i = i + 1
-
array[j] = array[i] # (3)100,17,510, 30,510 (5) 00,17,30, 30, 510
-
# i --> i j i-->ij
-
# ---------------------------------------------
-
-
# 做完第一轮while比较之后,list被分成了两个list,且i=j
-
array[i] = temp # (6)100,17,30,104,510 这是第一轮结束之后的情况.
-
# ij
-
# 此时,以第一轮选择的temp为分割点,分成两个list.左边list里的项都比temp小,右边list里的项都比temp大
-
# 递归前后半区
-
quick_sort(array, begin, i - 1)
-
quick_sort(array, j + 1, end)
-
return array
-
-
print("The sorted result is : ")
-
quick_sort(num_list, 0, len(num_list)-1)
-
print(num_list)
分享标题:python快速排序实现
标题网址:
http://cxhlcq.com/article/gcdohc.html
-
在线咨询

微信咨询


电话咨询
-
028-86922220(工作日)
18980820575(7×24)
-

提交需求
-

返回顶部