下方为递归排序
from random import randint
nums=[randint(1,10) for i in range(10)]
def qsort(seq):
if len(seq)<2:
return seq
middle=seq[0]
smaller=[]
larger=[]
for data in seq[1:]:
if data > middle: #改变大小号可以使得排序是从大到小还是从小到大。
smaller.append(data)
else:
larger.append(data)
return qsort(smaller)+[middle]+qsort(larger)
# xseq=list.sort(seq)
if __name__=='__main__':
print(nums)
result=qsort(nums)
print(result)
下方为效果
[8, 4, 9, 7, 10, 1, 5, 8, 3, 9]
[10, 9, 9, 8, 8, 7, 5, 4, 3, 1]
稍作改变
from random import randint
nums=[randint(1,10) for i in range(10)]
def qsort(seq):
if len(seq)<2:
return seq
middle=seq[0]
smaller=[]
larger=[]
for data in seq[1:]:
if data < middle: #改变大小号可以使得排序是从大到小还是从小到大。
smaller.append(data)
else:
larger.append(data)
return qsort(smaller)+[middle]+qsort(larger)
# xseq=list.sort(seq)
if __name__=='__main__':
print(nums)
result=qsort(nums)
print(result)
改变后的排序结果
[10, 8, 9, 1, 3, 9, 2, 3, 5, 9]
[1, 2, 3, 3, 5, 8, 9, 9, 9, 10]
网友评论