-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path排序算法.py
57 lines (50 loc) · 1.45 KB
/
排序算法.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
# 排序算法
# 冒泡排序
def bubbleSort(arr):
for i in range(1,len(arr)):
for j in range(0,len(arr)-i):
if arr[j] > arr[j+1]:
arr[j],arr[j + 1] = arr[j + 1],arr[j]
return arr
print(bubbleSort([2,7,5,9,4,0,8,3,1,6]))
# 选择排序
def selectionSort(arr):
for i in range(len(arr) - 1):
# 记录最小数的索引
minIndex = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
# i 不是最小数时,将 i 和最小数进行交换
if i != minIndex:
arr[i], arr[minIndex] = arr[minIndex], arr[i]
return arr
print(selectionSort([2,7,5,9,4,0,8,3,1,6]))
# 插入排序
def insertionSort(arr):
for i in range(len(arr)):
preIndex = i-1
current = arr[i]
while preIndex >= 0 and arr[preIndex] > current:
arr[preIndex+1] = arr[preIndex]
preIndex -= 1
arr[preIndex+1] = current
return arr
print(insertionSort([2,7,5,9,4,0,8,3,1,6]))
# 希尔排序
def shellSort(arr):
import math
gap=1
while(gap < len(arr)/3):
gap = gap*3+1
while gap > 0:
for i in range(gap,len(arr)):
temp = arr[i]
j = i-gap
while j >=0 and arr[j] > temp:
arr[j+gap]=arr[j]
j-=gap
arr[j+gap] = temp
gap = math.floor(gap/3)
return arr
print(shellSort([2,7,5,9,4,0,8,3,1,6]))