利用python进行归并排序,摘抄自http://blog.csdn.net/minxihou/article/details/51821052
“代码真的不是一气呵成的,而且也不是想当然写出来的。可能需要反复断点中断来查看是否有逻辑错误。在理解了问题的基础下我们需要先把大体的代码框架最好先写出来,特别是主要的逻辑判断语句。但是不需要太care我循环体或者判断里面语句怎么实现,当你把这一步做到的时候能避免很多不必要的错误发生。”
1 import random 2 3 def ConfiationAlgorithm(str): 4 if len(str) <= 1: #子序列 5 return str 6 mid = (len(str) // 2) 7 left = ConfiationAlgorithm(str[:mid])#递归的切片操作 8 right = ConfiationAlgorithm(str[mid:]) 9 result = [] 10 #i,j = 0,0 11 12 while len(left) > 0 and len(right) > 0: 13 if (left[0] <= right[0]): 14 #result.append(left[0]) 15 result.append(left.pop(0)) 16 #i+= 1 17 else: 18 #result.append(right[0]) 19 result.append(right.pop(0)) 20 #j+= 1 21 22 if (len(left) > 0): 23 result.extend(ConfiationAlgorithm(left)) 24 else: 25 result.extend(ConfiationAlgorithm(right)) 26 return result 27 28 if __name__ == ‘__main__‘: 29 a = [20,30,64,16,8,0,99,24,75,100,69] 30 print(ConfiationAlgorithm(a)) 31 b = [random.randint(1,1000) for i in range(10)] 32 print(ConfiationAlgorithm(b))
另一种思路
1 def merge(left, right): 2 i, j = 0, 0 3 result = [] 4 while i < len(left) and j < len(right): 5 if left[i] <= right[j]: 6 result.append(left[i]) 7 i += 1 8 else: 9 result.append(right[j]) 10 j += 1 11 result += left[i:] 12 result += right[j:] 13 return result 14 15 def merge_sort(lists): 16 # 归并排序 17 if len(lists) <= 1: 18 return lists 19 num = len(lists) / 2 20 left = merge_sort(lists[:num]) 21 right = merge_sort(lists[num:]) 22 return merge(left, right)
时间: 2024-12-26 12:48:41