Skip to content

Commit d68dad5

Browse files
taseikyocclauss
andauthored
Update sorts/quick_sort_3_partition.py (TheAlgorithms#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 <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 4afe2b3 commit d68dad5

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

Diff for: sorts/quick_sort_3_partition.py

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
def quick_sort_3partition(sorting, left, right):
1+
def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
22
if right <= left:
33
return
44
a = i = left
@@ -18,7 +18,36 @@ def quick_sort_3partition(sorting, left, right):
1818
quick_sort_3partition(sorting, b + 1, right)
1919

2020

21+
def three_way_radix_quicksort(sorting: list) -> list:
22+
"""
23+
Three-way radix quicksort:
24+
https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort
25+
First divide the list into three parts.
26+
Then recursively sort the "less than" and "greater than" partitions.
27+
28+
>>> three_way_radix_quicksort([])
29+
[]
30+
>>> three_way_radix_quicksort([1])
31+
[1]
32+
>>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1])
33+
[-5, -2, -2, 0, 1, 1]
34+
>>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1])
35+
[-1, 0, 0, 1, 1, 2, 2, 2, 5, 5]
36+
"""
37+
if len(sorting) <= 1:
38+
return sorting
39+
return (
40+
three_way_radix_quicksort([i for i in sorting if i < sorting[0]])
41+
+ [i for i in sorting if i == sorting[0]]
42+
+ three_way_radix_quicksort([i for i in sorting if i > sorting[0]])
43+
)
44+
45+
2146
if __name__ == "__main__":
47+
import doctest
48+
49+
doctest.testmod(verbose=True)
50+
2251
user_input = input("Enter numbers separated by a comma:\n").strip()
2352
unsorted = [int(item) for item in user_input.split(",")]
2453
quick_sort_3partition(unsorted, 0, len(unsorted) - 1)

0 commit comments

Comments
 (0)