-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquicksort.py
More file actions
74 lines (62 loc) · 2.23 KB
/
Copy pathquicksort.py
File metadata and controls
74 lines (62 loc) · 2.23 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#<editor-fold desc="Imports">
import insertionsort as ins
#</editor-fold>
class QuickSort(object):
def GetMedianOfThreeIndex(self, array, start, end):
def Switch(index):
nonlocal medianIndex
return {
0: start,
1: medianIndex,
2: end - 1
}[index] # Makeshift switch statement
def GetMedianIndex(start, length):
if length % 2 == 0:
return start + length // 2 - 1
else:
return start + length // 2
def Median(i, j, k):
if i < j:
return j if j < k else k
else:
return i if i < k else k
medianIndex = GetMedianIndex(start, end - start)
return Median(array[start], array[end - 1], array[medianIndex])
def Partition(self, array, start, end, isMedianOfThree):
medianIndex = QuickSort.GetMedianOfThreeIndex(self, array, start, end) if isMedianOfThree else start
pivot = array[medianIndex]
array[medianIndex], array[start] = array[start], pivot
i = start + 1
for j in range(start + 1, end):
if array[j] < pivot:
array[j], array[i] = array[i], array[j]
i += 1
array[start], array[i - 1] = array[i - 1], array[start]
return i - 1 # New Pivot
def Sort(self, arr, isMedianOfThree):
stack = []
stack.append(0)
stack.append(len(arr))
while len(stack) > 0:
end = stack.pop()
start = stack.pop()
if end - start < 2: continue
p = QuickSort.Partition(self, arr, start, end, isMedianOfThree)
stack.append(p + 1)
stack.append(end)
stack.append(start)
stack.append(p)
def QuickSort(self, arr):
if len(arr) <= 1:
return arr
QuickSort.Sort(self, arr, False)
return arr
def SortMedianOfThree(self, arr):
if len(arr) <= 1:
return arr
QuickSort.Sort(self, arr, True)
return arr
def OptimisedSort(self, arr):
if len(arr) > 16:
return QuickSort.SortMedianOfThree(self, arr)
return ins.InsertionSort().Sort(arr)