-
Notifications
You must be signed in to change notification settings - Fork 12
/
Quick sort.py
41 lines (28 loc) · 1.03 KB
/
Quick sort.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
# Quick sort in Python
# Function to partition the array on the basis of pivot element
def partition(array, low, high):
# Select the pivot element
pivot = array[high]
i = low - 1
# Put the elements smaller than pivot on the left and greater
#than pivot on the right of pivot
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
# Select pivot position and put all the elements smaller
# than pivot on left and greater than pivot on right
pi = partition(array, low, high)
# Sort the elements on the left of pivot
quickSort(array, low, pi - 1)
# Sort the elements on the right of pivot
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)