forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_5.py
55 lines (46 loc) · 1.17 KB
/
Exercise_5.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Python program for implementation of Quicksort
# This function is same in both iterative and recursive
# Time Complexity = O(logn)
# Space Complexity = O(1)
def partition(arr, l, h):
# write your code here
i = (l - 1)
pivot = arr[h]
for j in range(l, h):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[h] = arr[h], arr[i + 1]
return i + 1
def quickSortIterative(arr, l, h):
# write your code here
size = h - l + 1
stack = [0] * (size)
top = -1
top = top + 1
stack[top] = l
top = top + 1
stack[top] = h
while top >= 0:
h = stack[top]
top = top - 1
l = stack[top]
top = top - 1
p = partition(arr, l, h)
if p - 1 > l:
top = top + 1
stack[top] = l
top = top + 1
stack[top] = p - 1
if p + 1 < h:
top = top + 1
stack[top] = p + 1
top = top + 1
stack[top] = h
# Driver Code
arr = [4, 2, 6, 9, 8]
n = len(arr)
# Calling quickSort function
quickSortIterative(arr, 0, n - 1)
for i in range(n):
print(arr[i], end=" ")