Update sorts/quick_sort_3_partition.py (#2507)

* Update sorts/quick_sort_3partition.py

Another quick sort algorithm, returns a new sorted list

* Update sorts/quick_sort_3_partition.py

rename quick_sort_3partition to quick_sort_3part

* Update sorts/quick_sort_3_partition.py

rename quick_sort_3part to three_way_radix_quicksort
Three-way radix quicksort:
https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort
First divide the list into three parts.
Then recursively sort the "less than" and "greater than" partitions.

* Update sorts/quick_sort_3_partition.py

Co-authored-by: Christian Clauss <cclauss@me.com>

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Lewis Tian 2020-09-29 19:55:48 +08:00 committed by GitHub
parent d95d643351
commit e166350509
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
def quick_sort_3partition(sorting, left, right): def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
if right <= left: if right <= left:
return return
a = i = left a = i = left
@ -18,7 +18,36 @@ def quick_sort_3partition(sorting, left, right):
quick_sort_3partition(sorting, b + 1, right) quick_sort_3partition(sorting, b + 1, right)
def three_way_radix_quicksort(sorting: list) -> list:
"""
Three-way radix quicksort:
https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort
First divide the list into three parts.
Then recursively sort the "less than" and "greater than" partitions.
>>> three_way_radix_quicksort([])
[]
>>> three_way_radix_quicksort([1])
[1]
>>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1])
[-5, -2, -2, 0, 1, 1]
>>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1])
[-1, 0, 0, 1, 1, 2, 2, 2, 5, 5]
"""
if len(sorting) <= 1:
return sorting
return (
three_way_radix_quicksort([i for i in sorting if i < sorting[0]])
+ [i for i in sorting if i == sorting[0]]
+ three_way_radix_quicksort([i for i in sorting if i > sorting[0]])
)
if __name__ == "__main__": if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
user_input = input("Enter numbers separated by a comma:\n").strip() user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")] unsorted = [int(item) for item in user_input.split(",")]
quick_sort_3partition(unsorted, 0, len(unsorted) - 1) quick_sort_3partition(unsorted, 0, len(unsorted) - 1)