-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathExercise_5.py
More file actions
54 lines (43 loc) · 1.05 KB
/
Exercise_5.py
File metadata and controls
54 lines (43 loc) · 1.05 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Python program for implementation of Quicksort
# This function is same in both iterative and recursive
def partition(arr, l, h):
#write your code here
pivot = arr[h]
i = l - 1
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
stack = [0] * (h - l + 1)
top = -1
top += 1
stack[top] = l
top += 1
stack[top] = h
while top >= 0:
h = stack[top]
top -= 1
l = stack[top]
top -= 1
p = partition(arr, l, h)
if p - 1 > l:
top += 1
stack[top] = l
top += 1
stack[top] = p - 1
if p + 1 < h:
top += 1
stack[top] = p + 1
top += 1
stack[top] = h
# Driver code to test above
arr = [1, 7, 18, 4, 5, 90]
n = len(arr)
quickSortIterative(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i])