-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort_mergeSort.py
More file actions
89 lines (78 loc) · 2.1 KB
/
quickSort_mergeSort.py
File metadata and controls
89 lines (78 loc) · 2.1 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
84
85
86
87
88
89
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 19:51:45 2020
@author: zsl
"""
'''
(2)给定 n 个元素,这些元素是无序的,分别使用合并排序和快速
排序对 n 个元素进行排序。
要求:写出两种排序算法的完整程序, 测试 两种算法的时间复杂度,对
比它们的优劣
'''
# s start ; e end,快排
def Quick_sort(n, s, e):
if s >= e:
return
x = n[s]
low = s
high = e
while low < high:
while low < high and x < n[high]:
high = high - 1
n[low] = n[high]
while low < high and x >= n[low]:
low = low + 1
n[high] = n[low]
n[low] = x
Quick_sort(n, s, low - 1)
Quick_sort(n, low + 1, e)
# 归并排序
# 对有序的两个序列进行归并
def merge(L1, L2):
e1 = len(L1) - 1
e2 = len(L2) - 1
s1, s2= 0, 0
L3 = []
while s1 <= e1 and s2 <= e2:
if L1[s1] > L2[s2]:
L3.append(L2[s2])
s2 = s2 + 1
else:
L3.append(L1[s1])
s1 = s1 + 1
while s1 > e1 and s2 <= e2:
L3.append(L2[s2])
s2 = s2 + 1
while s1 <= e1 and s2 > e2:
L3.append(L1[s1])
s1 = s1 + 1
return L3
# 拆分,调用归并进行排序
def merge_sort(n):
if len(n) <= 1:
return n
mid = len(n) // 2
left = merge_sort(n[:mid])
right = merge_sort(n[mid:])
return merge(left, right)
import numpy as np
import time
def main2():
n = np.random.permutation(1000000).tolist()
print("对含有一百万个数的随机list")
# n = [5, 3, 4, 2, 1, 6]
# print(n)
print('归并排序开始')
a = time.time()
merge_sort(n)
b = time.time()
# print('归并排序之后的结果:',merge_sort(n))
print('结束')
print('快速排序开始')
c = time.time()
Quick_sort(n,0,len(n)-1)
d = time.time()
# print('快速排序之后的结果:', n)
print('结束')
print("merge sort costs %.6f seconds, quick sort costs %.6f seconds" % (b-a,d-c))
main2()