-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
37 lines (33 loc) · 1.12 KB
/
quick_sort.py
File metadata and controls
37 lines (33 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def quick_sort(data_list, start, end):
"""
Sorts a list using the Quick Sort algorithm with pivot-based partitioning.
"""
# Base calculation for the pivot and pointers
mid = (start + end) // 2
pivot = data_list[mid]
i = start
j = end
# Partitioning loop
while i <= j:
# Move i forward while elements are smaller than the pivot
while data_list[i] < pivot:
i += 1
# Move j backward while elements are larger than the pivot
while data_list[j] > pivot:
j -= 1
# Swap elements if pointers haven't crossed
if i <= j:
data_list[i], data_list[j] = data_list[j], data_list[i]
i += 1
j -= 1
# Recursively sort the resulting partitions
if start < j:
quick_sort(data_list, start, j)
if i < end:
quick_sort(data_list, i, end)
# Testing the implementation
if __name__ == "__main__":
test_list = [25, 33, 35, 12, 37, 86, 92, 57]
print(f"Original list (Quick): {test_list}")
quick_sort(test_list, 0, len(test_list) - 1)
print(f"Sorted list (Quick): {test_list}")