【郑州校区】数据结构学习(shell排序和归并排序)
[AppleScript] 纯文本查看 复制代码 # coding=utf-8[/align]
# shell排序
# 参数alist:被被排序的列表
def shellsort(alist):
gap = len(alist) / 2
while gap > 0:
for i in range(gap):
shellinsert(alist, i, gap)
gap = gap / 2
print alist
#根据步长进行插入排序
def shellinsert(alist, start, gap):
for i in range(start + gap, len(alist), gap):
temp = alist[i]
position = i
while position >= gap and alist[position - gap] > temp:
alist[position] = alist[position - gap]
position = position - gap
alist[position] = temp
# 归并排序
# 参数alist:被被排序的列表
def mege_sort(alist):
if len(alist) <= 1:
return alist
num = int(len(alist) / 2)
leftList = mege_sort(alist[:num])
rightList = mege_sort(alist[num:])
return mege(leftList, rightList)
#将两个列表合并为一个列表进行返回
def mege(leftList, rightList):
l = 0
r = 0
result = []
while l < len(leftList) and r < len(rightList):
if leftList[l] < rightList[r]:
result.append(leftList[l])
l += 1
else:
result.append(rightList[r])
r += 1
result = result + leftList[l:]
result = result + rightList[r:]
return result
alist = [9, 8, 9, 9, 7, 6, 5, 4, 3, 2, 1]
if __name__ == '__main__':
# shellsort(alist)
result = mege_sort(alist)
print alist
print result
传智播客·黑马程序员郑州校区地址 河南省郑州市 高新区长椿路11号大学科技园(西区)东门8号楼三层
|