近几天,重新看了一些排序算法方面的资料,发现自己对排序算法的理解还有很多不足之处。所以重新用Python实现了一些排序算法。
现记录一下,以备日后查看。
主要算法实现思想详见Brad Miller 和 David Ranum的《Problem Solving with Algorithms and Data Structures》一书。
1. 冒泡排序
def bubble(alist):
for i in range(len(alist) - 1, 0, -1):
for j in range(i):
if alist[j] > alist[j+1]:
tmp = alist[j]
alist[j] = alist[j+1]
alist[j+1] = tmp
>>> alist = [random.randint(0, 100) for i in range(10)]
>>> alist
[96, 78, 84, 39, 72, 6, 33, 58, 43, 83]
>>> bubble(alist)
>>> alist
[6, 33, 39, 43, 58, 72, 78, 83, 84, 96]
2. 选择排序
def selection(alist):
for i in range(len(alist)):
for j in range(i+1, len(alist)):
if alist[i] > alist[j]:
tmp = alist[i]
alist[i] = alist[j]
alist[j] = tmp
>>> alist = [random.randint(0,100) for i in range(10)]
>>> alist
[64, 94, 19, 58, 9, 49, 100, 72, 42, 84]
>>> selection(alist)
>>> alist
[9, 19, 42, 49, 58, 64, 72, 84, 94, 100]
3. 插入排序
def insertion(alist):
for i in range(1, len(alist)):
cv = alist[i]
j = i - 1
while j >= 0 and alist[j] > cv:
alist[j+1] = alist[j]
j -= 1
alist[j+1] = cv
>>> alist = [random.randint(0,100) for i in range(10)]
>>> alist
[72, 66, 58, 72, 58, 76, 62, 39, 75, 64]
>>> insertion(alist)
>>> alist
[39, 58, 58, 62, 64, 66, 72, 72, 75, 76]
4. 希尔排序
def incrInsert(alist, start, incr):
for i in range(start+incr, len(alist), incr):
cv = alist[i]
j = i - incr
while j >= 0 and alist[j] > cv:
alist[j+incr] = alist[j]
j -= incr
alist[j+incr] = cv
def shell(alist):
incr = len(alist) // 2
while incr > 0:
for start in range(incr):
incrInsert(alist, start, incr)
incr //= 2
>>> alist = [random.randint(0, 100) for i in range(10)]
>>> alist
[38, 65, 6, 97, 5, 9, 80, 84, 90, 0]
>>> shell(alist)
>>> alist
[0, 5, 6, 9, 38, 65, 80, 84, 90, 97]
5. 归并排序
def merge(alist):
if len(alist) > 1:
mid = len(alist) // 2
left = alist[:mid]
right = alist[mid:]
merge(left)
merge(right)
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
alist[k] = right[j]
j += 1
else:
alist[k] = left[i]
i += 1
k += 1
while i < len(left):
alist[k] = left[i]
i += 1
k += 1
while j < len(right):
alist[k] = right[j]
j += 1
k += 1
>>> alist = [random.randint(0, 100) for i in range(10)]
>>> alist
[56, 99, 24, 19, 59, 32, 47, 97, 4, 31]
>>> merge(alist)
>>> alist
[4, 19, 24, 31, 32, 47, 56, 59, 97, 99]