Skip to content

Commit 9ef04c1

Browse files
Merge pull request #199 from Pradeepsingh61/add-python-quick-sort
Add Quick Sort implementation in Pytho
2 parents 0a0e1c5 + 4aa70c7 commit 9ef04c1

1 file changed

Lines changed: 103 additions & 0 deletions

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""
2+
Quick Sort Algorithm
3+
Time Complexity: O(n log n) average, O(n²) worst case
4+
Space Complexity: O(log n) due to recursion stack
5+
Author: Karanjot Singh
6+
Date: October 2025
7+
Hacktoberfest 2025
8+
"""
9+
10+
def partition(arr, low, high):
11+
"""
12+
Partition function for quick sort
13+
Places pivot element at correct position and arranges smaller elements to left
14+
and greater elements to right of pivot
15+
16+
Args:
17+
arr: List to partition
18+
low: Starting index
19+
high: Ending index
20+
21+
Returns:
22+
Partition index
23+
"""
24+
pivot = arr[high]
25+
i = low - 1
26+
27+
for j in range(low, high):
28+
if arr[j] <= pivot:
29+
i += 1
30+
arr[i], arr[j] = arr[j], arr[i]
31+
32+
arr[i + 1], arr[high] = arr[high], arr[i + 1]
33+
return i + 1
34+
35+
36+
def quick_sort(arr, low=0, high=None):
37+
"""
38+
Quick sort implementation using divide and conquer
39+
40+
Args:
41+
arr: List to sort
42+
low: Starting index (default 0)
43+
high: Ending index (default None, uses len(arr)-1)
44+
"""
45+
if high is None:
46+
high = len(arr) - 1
47+
48+
if low < high:
49+
pi = partition(arr, low, high)
50+
quick_sort(arr, low, pi - 1)
51+
quick_sort(arr, pi + 1, high)
52+
53+
54+
def quick_sort_wrapper(arr):
55+
"""
56+
Wrapper function that returns sorted array
57+
58+
Args:
59+
arr: List to sort
60+
61+
Returns:
62+
Sorted list
63+
"""
64+
arr_copy = arr.copy()
65+
quick_sort(arr_copy)
66+
return arr_copy
67+
68+
69+
# Test cases
70+
if __name__ == "__main__":
71+
print("=== Quick Sort Algorithm ===\n")
72+
73+
# Test case 1: Random array
74+
test1 = [64, 34, 25, 12, 22, 11, 90]
75+
print(f"Original array: {test1}")
76+
sorted1 = quick_sort_wrapper(test1)
77+
print(f"Sorted array: {sorted1}")
78+
79+
# Test case 2: Already sorted
80+
test2 = [1, 2, 3, 4, 5]
81+
print(f"\nOriginal array: {test2}")
82+
sorted2 = quick_sort_wrapper(test2)
83+
print(f"Sorted array: {sorted2}")
84+
85+
# Test case 3: Reverse sorted
86+
test3 = [9, 7, 5, 3, 1]
87+
print(f"\nOriginal array: {test3}")
88+
sorted3 = quick_sort_wrapper(test3)
89+
print(f"Sorted array: {sorted3}")
90+
91+
# Test case 4: Array with duplicates
92+
test4 = [5, 2, 8, 2, 9, 1, 5]
93+
print(f"\nOriginal array: {test4}")
94+
sorted4 = quick_sort_wrapper(test4)
95+
print(f"Sorted array: {sorted4}")
96+
97+
# Test case 5: Single element
98+
test5 = [42]
99+
print(f"\nOriginal array: {test5}")
100+
sorted5 = quick_sort_wrapper(test5)
101+
print(f"Sorted array: {sorted5}")
102+
103+
print("\n✅ All test cases completed!")

0 commit comments

Comments
 (0)