forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_2.py
More file actions
51 lines (39 loc) · 1.24 KB
/
Exercise_2.py
File metadata and controls
51 lines (39 loc) · 1.24 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
#//Time Complexity :O(nlogn)
#// Space Complexity : O(logn)
#// Did this code successfully run on Leetcode : Yes
#// Any problem you faced while coding this : Forgot the algorithm and while implementing had difficulty in converting logic to code.
# Python program for implementation of Quicksort Sort
# give you explanation for the approach
def partition(arr,low,high):
#write your code here
#picking middle element for pivot
pivot = arr[(low + high) // 2]
i = low -1
j = high + 1
while True:
# moving i pointer to right
i += 1
while arr[i] < pivot:
i += 1
# moving j pointer to left
j -= 1
while arr[j] > pivot:
j -= 1
#pointer cross return j as pivot
if i >= j :
return j
arr[i], arr[j] = arr[j], arr[i]
# Function to do Quick sort
def quickSort(arr,low,high):
#write your code here
if low < high:
p = partition(arr,low,high)
quickSort(arr,low,p)
quickSort(arr,p+1,high)
# Driver code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i]),