Quick sort with lomuto partition (#3875)

* add quick sort algorithm with Lomuto partition

* fix(lomuto_partition): fix snake_case
This commit is contained in:
MarineJoker 2021-02-17 22:28:50 +08:00 committed by GitHub
parent d3ac521b63
commit 78ddb46066
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -18,6 +18,53 @@ def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
quick_sort_3partition(sorting, b + 1, right)
def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None:
"""
A pure Python implementation of quick sort algorithm(in-place)
with Lomuto partition scheme:
https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
:param sorting: sort list
:param left: left endpoint of sorting
:param right: right endpoint of sorting
:return: None
Examples:
>>> nums1 = [0, 5, 3, 1, 2]
>>> quick_sort_lomuto_partition(nums1, 0, 4)
>>> nums1
[0, 1, 2, 3, 5]
>>> nums2 = []
>>> quick_sort_lomuto_partition(nums2, 0, 0)
>>> nums2
[]
>>> nums3 = [-2, 5, 0, -4]
>>> quick_sort_lomuto_partition(nums3, 0, 3)
>>> nums3
[-4, -2, 0, 5]
"""
if left < right:
pivot_index = lomuto_partition(sorting, left, right)
quick_sort_lomuto_partition(sorting, left, pivot_index - 1)
quick_sort_lomuto_partition(sorting, pivot_index + 1, right)
def lomuto_partition(sorting: list, left: int, right: int) -> int:
"""
Example:
>>> lomuto_partition([1,5,7,6], 0, 3)
2
"""
pivot = sorting[right]
store_index = left
for i in range(left, right):
if sorting[i] < pivot:
sorting[store_index], sorting[i] = sorting[i], sorting[store_index]
store_index += 1
sorting[right], sorting[store_index] = sorting[store_index], sorting[right]
return store_index
def three_way_radix_quicksort(sorting: list) -> list:
"""
Three-way radix quicksort: