-
Notifications
You must be signed in to change notification settings - Fork 459
/
Quick_Sort.py
36 lines (27 loc) · 1.21 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
# Best: O(nlog(n)) time | O(log(n)) space
# Average: O(nlog(n)) time | O(log(n)) space
# Worst: O(n^2) time | O(log(n)) space
def quickSort(array):
quickSortHelper(array, 0, len(array) - 1)
return array
def quickSortHelper(array, startIndex, endIndex):
if startIndex >= endIndex:
return
pivotIndex = startIndex
leftIndex = startIndex + 1
rightIndex = endIndex
while rightIndex >= leftIndex:
if array[leftIndex] > array[pivotIndex] and array[rightIndex] < array[pivotIndex]:
array[leftIndex], array[rightIndex] = array[rightIndex], array[leftIndex]
if array[leftIndex] <= array[pivotIndex]:
leftIndex += 1
if array[rightIndex] >= array[pivotIndex]:
rightIndex -= 1
array[rightIndex], array[pivotIndex] = array[pivotIndex], array[rightIndex]
leftSubArrayIsSmaller = rightIndex - 1 - startIndex < endIndex - (rightIndex + 1)
if leftSubArrayIsSmaller:
quickSortHelper(array, startIndex, rightIndex - 1)
quickSortHelper(array, rightIndex + 1, endIndex)
else:
quickSortHelper(array, rightIndex + 1, endIndex)
quickSortHelper(array, startIndex, rightIndex - 1)