原理简介:
归并排序是在归并的操作基础上采用分治法的排序方法;归并操作就是将两个有序的子列合并成一个有序总列,分治法就是通过二分法将序列不断分成子列。
python 代码:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from random import randint
#generate a unsorted list
origin = []
def randomList():
for i in xrange(0,10,1):
origin.append(randint(-10,10))
# print origin
def merge(origin,left,middle,right):
leftarray = origin[left:middle+1]
rightarray = origin[middle+1:right+1]
lindex = 0
rindex = 0
index = left
while lindex < len(leftarray) and rindex < len(rightarray):
if leftarray[lindex] < rightarray[rindex]:
origin[index] = leftarray[lindex]
lindex += 1
else:
origin[index] = rightarray[rindex]
rindex += 1
index += 1
while lindex < len(leftarray):
origin[index] = leftarray[lindex]
index += 1
lindex += 1
while rindex < len(rightarray):
origin[index] = rightarray[rindex]
index += 1
rindex += 1
def merge_sort(origin,begin,end):
if begin < end:
middle = (end + begin)/2
merge_sort(origin, begin, middle)
merge_sort(origin, middle + 1, end)
merge(origin, begin, middle, end)
if __name__ == '__main__':
randomList()
print origin
merge_sort(origin, 0, len(origin)-1)
print origin
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。