Skip to content

Commit fe4e455

Browse files
MarineJokershermanhui
authored andcommitted
Quick sort with lomuto partition (TheAlgorithms#3875)
* add quick sort algorithm with Lomuto partition * fix(lomuto_partition): fix snake_case
1 parent 620c848 commit fe4e455

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

sorts/quick_sort_3_partition.py

+47
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,53 @@ def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
1818
quick_sort_3partition(sorting, b + 1, right)
1919

2020

21+
def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None:
22+
"""
23+
A pure Python implementation of quick sort algorithm(in-place)
24+
with Lomuto partition scheme:
25+
https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
26+
27+
:param sorting: sort list
28+
:param left: left endpoint of sorting
29+
:param right: right endpoint of sorting
30+
:return: None
31+
32+
Examples:
33+
>>> nums1 = [0, 5, 3, 1, 2]
34+
>>> quick_sort_lomuto_partition(nums1, 0, 4)
35+
>>> nums1
36+
[0, 1, 2, 3, 5]
37+
>>> nums2 = []
38+
>>> quick_sort_lomuto_partition(nums2, 0, 0)
39+
>>> nums2
40+
[]
41+
>>> nums3 = [-2, 5, 0, -4]
42+
>>> quick_sort_lomuto_partition(nums3, 0, 3)
43+
>>> nums3
44+
[-4, -2, 0, 5]
45+
"""
46+
if left < right:
47+
pivot_index = lomuto_partition(sorting, left, right)
48+
quick_sort_lomuto_partition(sorting, left, pivot_index - 1)
49+
quick_sort_lomuto_partition(sorting, pivot_index + 1, right)
50+
51+
52+
def lomuto_partition(sorting: list, left: int, right: int) -> int:
53+
"""
54+
Example:
55+
>>> lomuto_partition([1,5,7,6], 0, 3)
56+
2
57+
"""
58+
pivot = sorting[right]
59+
store_index = left
60+
for i in range(left, right):
61+
if sorting[i] < pivot:
62+
sorting[store_index], sorting[i] = sorting[i], sorting[store_index]
63+
store_index += 1
64+
sorting[right], sorting[store_index] = sorting[store_index], sorting[right]
65+
return store_index
66+
67+
2168
def three_way_radix_quicksort(sorting: list) -> list:
2269
"""
2370
Three-way radix quicksort:

0 commit comments

Comments
 (0)