快速排序算法的Python实现
Posted 一枚野生程序员的进阶之路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序算法的Python实现相关的知识,希望对你有一定的参考价值。
本文为快速排序算法的Python实现。
标准快排:
#!/usr/bin/env python3
# coding=utf-8
from tqdm import tqdm
from copy import deepcopy
import random
import string
def partition(unsorted: list, begin: int, end: int) -> int:
v = unsorted[begin]
i = begin + 1
j = end
while True:
while unsorted[i] < v:
if i == end:
break
i += 1
while unsorted[j] > v:
if j == begin:
break
j -= 1
if i >= j:
break
unsorted[i], unsorted[j] = unsorted[j], unsorted[i]
i += 1
j -= 1
unsorted[begin], unsorted[j] = unsorted[j], unsorted[begin]
return j
def _quicksort(unsorted: list, begin: int, end: int):
if begin >= end:
return
j = partition(unsorted, begin, end)
_quicksort(unsorted, begin, j - 1)
_quicksort(unsorted, j + 1, end)
def quicksort(unsorted_list: list) -> list:
random.shuffle(unsorted_list)
begin, end = 0, len(unsorted_list) - 1
_quicksort(unsorted_list, begin, end)
return unsorted_list
if __name__ == '__main__':
for _ in tqdm(range(100000)):
l = list(map(int, (random.choice(string.digits) for i in range(random.randint(1, 100)))))
assert sorted(deepcopy(l)) == quicksort(deepcopy(l))
三切分法快排:
import random, string
from copy import deepcopy
from tqdm import tqdm
def _quicksort(unsorted: list, begin: str, end: str):
if begin >= end:
return
lt, gt = begin, end
v = unsorted[begin]
i = begin + 1
while i <= gt:
if unsorted[i] < v:
unsorted[lt], unsorted[i] = unsorted[i], unsorted[lt]
lt += 1
i += 1
elif unsorted[i] > v:
unsorted[i], unsorted[gt] = unsorted[gt], unsorted[i]
gt -= 1
else:
i += 1
_quicksort(unsorted, begin, lt - 1)
_quicksort(unsorted, gt + 1, end)
def quicksort(unsorted_list:list) -> list:
random.shuffle(unsorted_list)
begin, end = 0, len(unsorted_list) - 1
_quicksort(unsorted_list, begin, end)
return unsorted_list
if __name__ == '__main__':
for _ in tqdm(range(100000)):
l = list(map(int, (random.choice(string.digits) for i in range(random.randint(1, 100)))))
assert sorted(deepcopy(l)) == quicksort(deepcopy(l))
三切分还是更快一些的,因为一次可以排定多个值,而标准快排一次只能排定一个值。而且三切分法写起来也简单一些…
以上是关于快速排序算法的Python实现的主要内容,如果未能解决你的问题,请参考以下文章