源地址:雨馀时候夕阳红
归并排序的思想在于将数组一分为二,将数组两边排好序,再将两边排好序的数组融合形成一个排好序的数组,可以递归地进行这个一分为二的过程,直到数组中只有一个元素。
import random
class merge(object):
def get_andomNumber(self,num):
lists = []
i = 0
while i < num:
lists.append(random.randint(0, 100))
i += 1
return lists
def merge_sort(self,numbers,start,end):
if(end - start <= 0):
return numbers
pivot = int((start+end)/2)
self.merge_sort(numbers,0,pivot)
self.merge_sort(numbers,pivot+1,end)
left = 0
right = pivot+1
while(left <= right and right <= end):
if(numbers[right]>=numbers[left]):
left += 1
else:
tmp = numbers.pop(right)
numbers.insert(left,tmp)
right += 1
left += 1
return numbers
if __name__ == '__main__':
t = merge()
numbers = t.get_andomNumber(9)
# numbers = [87, 1, 43, 45, 11, 15, 13, 18, 98]
print(numbers)
print(t.merge_sort(numbers,0,8))