-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.py
101 lines (79 loc) · 2.01 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from random import randrange
def quicksort(list):
if len(list) > 1:
pivot = randrange(len(list))
left = []
right = []
for index, i in enumerate(list):
if index != pivot:
if i < list[pivot]:
left.append(i)
else:
right.append(i)
left = quicksort(left)
right = quicksort(right)
return left + [list[pivot]] + right
else:
return list
'''
def partition(list,low,high):
pivot = randrange(low,high+1)
#this swaps the random pivot with the last element
temp = list[pivot]
list[pivot] = list[high]
list[high] = temp
i = low
j = high -1
while i < j:
if list[i] > list[high]:
temp = list[i]
list[i] = list[j]
list[j] = temp
j -= 1
else:
i += 1
if(list[i] < list[high]):
temp = list[i+1]
list[i+1] = list[high]
list[high] = temp
return i+1
else:
temp = list[i]
list[i] = list[high]
list[high] = temp
return i
'''
def partition(list,low,high):
pivot = randrange(low,high+1)
#this swaps the random pivot with the last element
temp = list[pivot]
list[pivot] = list[high]
list[high] = temp
i = low
j = high -1
while i <= j:
if list[i] < list[high]:
if list[j] > list[high]:
temp = list[i]
list[i] = list[j]
list[j] = temp
j -= 1
i += 1
else:
j -= 1
else:
i += 1
temp = list[i]
list[i] = list[high]
list[high] = temp
return i
def cppquicksort(list, low, high):
if low < high:
pivot = partition(list, low, high)
cppquicksort(list, low, pivot-1)
cppquicksort(list, pivot+1, high )
def main():
list = [7,8,3,1,4,2,6,5]
cppquicksort(list, 0, 7)
print(list)
main()