python中归并排序
1 # coding=UTF-8 2 #!/usr/bin/python 3 4 import sys 5 6 def merge(nums, first, middle, last): 7 "merge" 8 #切片边界,左闭右开,从0开始 9 lnums = nums[ first:middle+1 ] 10 rnums = nums[ middle+1:last+1 ] 11 lnums.append(sys.maxint) 12 rnums.append(sys.maxint) 13 l = 0 14 r = 0 15 for i in range( first, last+1 ): 16 if lnums[l] < rnums[r]: 17 nums[i] = lnums[l] 18 l+=1 19 else: 20 nums[i] = rnums[r] 21 r+=1 22 23 def merge_sort(nums, first, last): 24 """mergesort 25 mergesort函数中传递的是下标,不是元素的个数 26 """28 if first < last: 29 middle = (first + last)/2 30 #print "middle in loop", count, "is:", middle 32 merge_sort(nums, first, middle) 33 merge_sort(nums, middle+1, last) 34 merge(nums,first, middle, last) 35 #print "loops:",count,">>", nums 36 37 38 39 if __name__ == '__main__': 40 nums = [10, 8, 4, -1, 2, 6, 7, 3] 41 print "nums is ", nums 42 merge_sort(nums, 0, 7) 43 print "merge_sort", nums
/usr/bin/python2.7 /root/PycharmProjects/Sort/merge-sort.py
nums is [10, 8, 4, -1, 2, 6, 7, 3]
merge_sort [-1, 2, 3, 4, 6, 7, 8, 10]
Process finished with exit code 0
勤苦修行得自在,道力有边边亦无边!