python 实现排序算法(二)-合并排序(递归法)

 #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 22:28:09 2017 @author: livermorium116
""" import random class MergeSortedByCur():
def __init__(self, data):
self.data = data
#print("ORIGIN DATA:", self.data)
self.CountCur=0
self.Results=self.MergeSort(self.data)
def MergeSort(self,data): if len(data) <= 1:
return data
num = int(len(data)/2)
Left = self.MergeSort(data[:num])
Right = self.MergeSort(data[num:])
#print("LEFT:",Left,"RIGHT:",Right)
self.CountCur += 1
#print ("%d Cursions:"%(self.CountCur))
return self.Merge(Left, Right) def Merge(self,left, right):
R, L = 0, 0
result = []
while L < len(left ) and R < len(right ):
if left[L] < right[R]:
result.append(left[L])
L += 1
else:
result.append(right[R])
R += 1
result.extend(left[L:])
result.extend(right[R:])
#print("MergeSorted DATA:",result)
return result if __name__ == "__main__":
data = [random.randint(1,100) for i in range(13)]
print(data)
print MergeSortedByCur(data).Results
上一篇:Python之常见算法介绍


下一篇:jQuery MiniUI开发系列之:安装部署