-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument1.txt
More file actions
29 lines (23 loc) · 947 Bytes
/
document1.txt
File metadata and controls
29 lines (23 loc) · 947 Bytes
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
/hi
# Last element will be the pivot and the first element the pointer
pivot, ptr = nums[r], l
for i in range(l, r):
if nums[i] <= pivot:
# Swapping values smaller than the pivot to the front
nums[i], nums[ptr] = nums[ptr], nums[i]
ptr += 1
# Finally swapping the last element with the pointer indexed number
nums[ptr], nums[r] = nums[r], nums[ptr]
return ptr
def quicksort(l, r, nums):
if len(nums) == 1: # Terminating Condition for recursion. VERY IMPORTANT!
return nums
if l < r:
pi = partition(l, r, nums)
quicksort(l, pi-1, nums) # Recursively sorting the left values
quicksort(pi+1, r, nums) # Recursively sorting the right values
return nums
example = [2, 5, 6, 1, 4, 6, 2, 4, 7, 8]
result = [1, 2, 2, 4, 4, 5, 6, 6, 7, 8]
# As you can see, it works for duplicates too
print(quicksort(0, len(example)-1, example))