1
+ # function to find the partition position
2
+ def partition (arr , lb , hb ):
3
+
4
+ # choose the rbtmost element as pivot
5
+ pivot = arr [hb ]
6
+
7
+ # pointer for greater element
8
+ i = lb - 1
9
+
10
+ # traverse through all elements
11
+ # compare each element with pivot
12
+ for j in range (lb , hb ):
13
+ if arr [j ] <= pivot :
14
+ # if element smaller than pivot is found
15
+ # swap it with the greater element pointed by i
16
+ i = i + 1
17
+
18
+ # swapping element at i with element at j
19
+ (arr [i ], arr [j ]) = (arr [j ], arr [i ])
20
+
21
+ # swap the pivot element with the greater element specified by i
22
+ (arr [i + 1 ], arr [hb ]) = (arr [hb ], arr [i + 1 ])
23
+
24
+ # return the position from where partition is done
25
+ return i + 1
26
+
27
+ def quickSort (arr ,lb ,ub ):
28
+ if (lb < ub ):
29
+ loc = partition (arr ,lb ,ub )
30
+ quickSort (arr ,lb ,loc - 1 )
31
+ quickSort (arr ,loc + 1 ,ub )
32
+
33
+ data = [8 , 7 , 2 , 1 , 0 , 9 , 6 ]
34
+ print ("Unsorted Array: " )
35
+ print (data )
36
+
37
+ size = len (data )
38
+
39
+ quickSort (data , 0 , size - 1 )
40
+
41
+ print ('Sorted Array in Ascending Order:' )
42
+ print (data )
43
+
44
+ #Time complexity: O(n*log n)
45
+ #Space complexity: O(log n)
0 commit comments