Skip to content

Commit 2d38fee

Browse files
adding quicksort exercise solution
1 parent 27ede19 commit 2d38fee

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

3.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
def swap(a, b, arr):
2+
if a!=b:
3+
tmp = arr[a]
4+
arr[a] = arr[b]
5+
arr[b] = tmp
6+
7+
# Sorts a (portion of an) array, divides it into partitions, then sorts those
8+
def quicksort(A, lo, hi):
9+
if lo >= 0 and lo < hi:
10+
lt, gt = partition(A, lo, hi) # Multiple return values
11+
quicksort(A, lo, lt - 1)
12+
quicksort(A, gt + 1, hi)
13+
14+
# Divides array into three partitions
15+
def partition(A, lo, hi):
16+
# Pivot value
17+
pivot = A[(lo + hi) // 2] # Choose the middle element as the pivot (integer division)
18+
19+
# Lesser, equal and greater index
20+
lt = lo
21+
eq = lo
22+
gt = hi
23+
24+
# Iterate and compare all elements with the pivot
25+
26+
while eq <= gt:
27+
if A[eq] < pivot:
28+
# Swap the elements at the equal and lesser indices
29+
swap(eq, lt, A)
30+
# Increase lesser index
31+
lt += 1
32+
# Increase equal index
33+
eq += 1
34+
elif A[eq] > pivot:
35+
# Swap the elements at the equal and greater indices
36+
swap(eq, gt, A)
37+
# Decrease greater index
38+
gt -= 1
39+
else: # A[eq] == pivot
40+
# Increase equal index
41+
eq += 1
42+
43+
# Return lesser and greater indices
44+
return lt, gt
45+
46+
elements = [11,9,29,7,2,15,28]
47+
# elements = ["mona", "dhaval", "aamir", "tina", "chang"]
48+
quicksort(elements, 0, len(elements)-1)
49+
print(elements)
50+
51+
tests = [
52+
[11,9,29,7,2,15,28],
53+
[3, 7, 9, 11],
54+
[25, 22, 21, 10],
55+
[29, 15, 28],
56+
[],
57+
[6]
58+
]
59+
60+
try:
61+
# Your script's entry point, e.g., function calls
62+
for elements in tests:
63+
quicksort(elements, 0, len(elements)-1)
64+
print(f'sorted array: {elements}')
65+
except Exception as e:
66+
print(f"Error occurred: {e}")

0 commit comments

Comments
 (0)