-
Notifications
You must be signed in to change notification settings - Fork 0
/
0.sort.py
83 lines (66 loc) · 1.88 KB
/
0.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
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
from heapq import merge
class Solution():
def sort(self, arr, type="quick"):
if type=="quick":
return self.quickSort2(arr, 0, len(arr)-1)
if type=="merge":
return self.mergeSort2(arr, 0, len(arr)-1)
def quickSort(self, arr, l, r):
if l < r:
i = self.partition(arr, l, r)
self.quickSort(arr, l, i-1)
self.quickSort(arr, i+1, r)
return arr
def partition(self, arr, l, r):
j = l - 1
target = arr[r]
for i in range(l, r):
if arr[i] < target:
j += 1
arr[i], arr[j] = arr[j], arr[i]
j += 1
arr[j], arr[r] = arr[r], arr[j]
return j
def mergeSort(self, arr, l, r):
if l < r:
m = int((l + r - 1) / 2)
self.mergeSort(arr, l, m)
self.mergeSort(arr, m+1, r)
self.merge(arr, l, m, r)
return arr
def merge(self, arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create two tmp array to store the value
tmp1 = []
for i in range(l, m+1):
tmp1.append(arr[i])
tmp2 = []
for i in range(m+1, r+1):
tmp2.append(arr[i])
# merge two tmp array
i, j, q= 0, 0, l
while i < n1 and j < n2:
if tmp1[i] < tmp2[j]:
arr[q] = tmp1[i]
i += 1
else:
arr[q] = tmp2[j]
j += 1
q += 1
while i < n1:
arr[q] = tmp1[i]
q += 1
i += 1
while j < n2:
arr[q] = tmp2[j]
q += 1
j += 1
import time
time1 = time.time()
arr = [10, 7, 8, 9, 1, 5, 10, 7, 8, 9, 1, 5]
arr = [10, 7, 8, 9, 1, 5]
pro = Solution()
print(pro.sort(arr, type="merge"))
time2 = time.time()
print(time2-time1)