Skip to content

Commit c1cc3b2

Browse files
committed
add algorithm
1 parent 57ce67b commit c1cc3b2

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

Python算法学习/归并排序.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
平均,最好,最坏 都是 O(nlogn)
3+
"""
4+
5+
6+
def merge_sort(ls):
7+
mid = len(ls) // 2
8+
if len(ls) <= 1:
9+
return ls
10+
left = merge_sort(ls[:mid])
11+
right = merge_sort(ls[mid:])
12+
return merge(left, right)
13+
14+
15+
def merge(left, right):
16+
l, r = 0, 0
17+
result = []
18+
while l < len(left) and r < len(right):
19+
if ls[l] < ls[r]:
20+
result.append(ls[l])
21+
l += 1
22+
else:
23+
result.append(ls[r])
24+
r += 1
25+
result += left[l:]
26+
result += right[r:]
27+
return result
28+
29+
30+
ls = [1, 4, 68, 34, 66, 99, 312]
31+
merge_sort(ls)
32+
print(ls)

Python算法学习/快速排序.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''
2+
通过一趟排序将要排序的数据分割成独立的两部分,
3+
其中一部分的所有数据都比另外一部分的所有数据都要小,
4+
然后再按此方法对这两部分数据分别进行快速排序,
5+
整个排序过程可以递归进行,以此达到整个数据变成有序序列。
6+
'''
7+
8+
9+
def quick_sort(lists, left, right):
10+
if left >= right:
11+
return lists
12+
key = lists[left]
13+
low = left
14+
high = right
15+
while left < right:
16+
while left < right and lists[right] >= key:
17+
right -= 1
18+
lists[left] = lists[right]
19+
while left < right and lists[left] <= key:
20+
left += 1
21+
lists[right] = lists[left]
22+
lists[right] = key
23+
quick_sort(lists, low, left - 1)
24+
quick_sort(lists, left + 1, high)
25+
return lists
26+
27+
28+
arr = [2, 645, 1, 344, 546, 442, 89, 99, 76, 90]
29+
print(quick_sort(arr, 0, len(arr) - 1))

Python算法学习/快速排序二.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def quick_sort(ls, left, right):
2+
if left < right:
3+
mid = (left + right) // 2
4+
pivot = ls[mid]
5+
ls[mid], ls[right] = ls[right], ls[mid]
6+
boundary = left
7+
for index in range(left, right):
8+
if ls[index] < pivot:
9+
ls[index], ls[boundary] = ls[boundary], ls[index]
10+
boundary += 1
11+
ls[right], ls[boundary] = ls[boundary], ls[right]
12+
quick_sort(ls, left, boundary - 1)
13+
quick_sort(ls, boundary + 1, right)
14+
15+
16+
ls = [1, 3, 56, 23, 34, 99, 532, 4, 59]
17+
print('before:', ls)
18+
quick_sort(ls, 0, len(ls) - 1)
19+
print('after :', ls)

0 commit comments

Comments
 (0)