码迷,mamicode.com
首页 > 编程语言 > 详细

python代码 归并排序 merge sort

时间:2015-02-17 23:47:16      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:python   return   

   1:  def mergesort(seq):
   2:      if len(seq)<=1:
   3:          return seq
   4:      mid=len(seq)/2
   5:      left=mergesort(seq[:mid])
   6:      right=mergesort(seq[mid:])
   7:      return merge(left,right)
   8:   
   9:  def merge(left,right):
  10:      result=[]
  11:      i,j=0,0
  12:      while i<len(left) and j<len(right):
  13:          if left[i]<=right[j]:
  14:              result.append(left[i])
  15:              i+=1
  16:          else:
  17:              result.append(right[j])
  18:              j+=1
  19:      result+=left[i:]
  20:      result+=right[j:]
  21:      return result
  22:   
  23:  if __name__==‘__main__‘:
  24:      seq=[4,5,7,9,7,5,1,0,7,-2,3,-99,6]
  25:      print(mergesort(seq))