Python题目:对列表[37,41.12,35,22,98,16,7,45,31]进行排序。
这里不考虑.sort()方法。
代码语言:javascript复制#!/usr/bin/env python
#_*_coding:utf-8_*_
def merge(left, right):
i, j = 0, 0
result = []
#左右列表元素对比大小,然后加1
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = 1
else:
result.append(right[j])
j = 1
#将大的值追加到列表右边
result = left[i:]
result = right[j:]
return result
def merge_sort(lists):
# 如果长度小于等于1,退出循环返回列表值
if len(lists) <= 1:
return lists
# 取中间值,分成两个列表
num = len(lists)/2
# 重复操作,直到只有一个元素
left = merge_sort(lists[:num])
right = merge_sort(lists[num:])
# 调用对比函数
return merge(left, right)
if __name__ == "__main__":
lists = [37,41.12,35,22,98,16,7,45,31]
s= merge_sort(lists)
print s
查看结果:
代码语言:javascript复制[7, 16, 22, 31, 35, 37, 41.12, 45, 98]