forked from ArsalanKhairani/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.py
46 lines (35 loc) · 1.4 KB
/
QuickSort.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
################################################################################
## Copyright(c) Arsalan Khairani, 2014 ##
## Quick Sort ##
## ##
## Sort an array of integers using quick sort algorithm. ##
################################################################################
# Function: Given an array with its left and right indices returns the position
# of pivot
def Partition(arr, left, right):
pivot = arr[left] # Make the first element from left the pivot
i = left + 1
# This loop compare each entry with pivot
for j in range(left + 1, right + 1):
if arr[j] < pivot:
temp = arr[j]
arr[j] = arr[i]
arr[i] = temp
i += 1
print (arr)
arr[left] = arr[i - 1]
arr[i - 1] = pivot
# Returns the position of the pivot
return i - 1
# Function: Sort an array around the pivot
def QuickSort(arr, start, end):
# base case
if (end - start) <= 1:
return
# Choosing pivot method - Here
# partition sub routine
pivot = Partition(arr, start, end)
# Call recursion
QuickSort(arr, start, pivot - 1)
QuickSort(arr, pivot + 1, end)
return (arr)