Repository navigation
Expand file tree
/
Copy pathquick_sort.py
More file actions
83 lines (62 loc) · 2.11 KB
/
Copy pathquick_sort.py
File metadata and controls
83 lines (62 loc) · 2.11 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
75
76
77
78
79
80
81
82
83
class QuickSorter(object):
def __init__(self,array):
"""
Initialize QuickSorter with an array of numbers that should be sorted
"""
self.list = []
self.replace_list(array)
def replace_list(self, array):
if isinstance(array, list):
for i in array:
if not (isinstance(i,int) or isinstance(i, float)):
raise ValueError("all elements must be type number")
else:
raise AttributeError("search array must be list type")
self.sorted = False
self.list = array
def __quicksort(self, low, high):
size = high - low + 1
stack = [0] * (size)
top = -1
top = top + 1
stack[top] = low
top = top + 1
stack[top] = high
while top >= 0:
high = stack[top]
top = top - 1
low = stack[top]
top = top - 1
partition = self.__partition( low, high )
if partition-1 > low:
top = top + 1
stack[top] = low
top = top + 1
stack[top] = partition - 1
if partition+1 < high:
top = top + 1
stack[top] = partition + 1
top = top + 1
stack[top] = high
def __partition(self,low,high):
i = ( low - 1 )
x = self.list[high]
for j in range(low , high):
if self.list[j] <= x:
i = i+1
self.list[i],self.list[j] = self.list[j],self.list[i]
self.list[i+1],self.list[high] = self.list[high],self.list[i+1]
return (i+1)
def sort(self):
"""
Executing Hoare partition scheme quick sort algorithm, iterativly
"""
self.__quicksort( 0, len(self.list) - 1 )
self.sorted = True
def result(self):
"""
Return the sorted list, and sort before if not already sorted
"""
if not self.sorted:
self.sort()
return self.list