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

python中的归并排序

时间:2014-05-18 09:16:53      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:归并排序   python   合并   算法   

       本来在博客上看到用python写的归并排序的程序,然后自己跟着他写了一下,结果发现是错的,不得不自己操作。而自己对python不是很了解所以就变百度边写,终于在花了半个小时之后就写好了。

def merge(a, first, end, temp):
	if first < end:
		mid = (first+end)//2
		merge(a, first, mid, temp) #前半部分拍好序
		merge(a, mid+1, end, temp) #后半部分拍好序
		merger(a, first, mid, end, temp) #每次对前面拍好序的两个数组进行合并
	else:
		return

def merger(a, first, mid, end, temp):
	i = first
	j = mid + 1
	k = 0
	while (i <= mid and j < end):
		if (a[i] < a[j]):
			temp.append(a[i])
			i = i + 1
		else:
			temp.append(a[j])
			j = j + 1
	while (i <= mid):
		temp.append(a[i])
		i = i + 1
	while (j < end):
		temp.append(a[j])
		j = j + 1

	for i in range(len(temp)):
		a[first+i] = temp[i]
	temp.clear() #这里记得要清零

a = [1,5,38,78, 4, 56, 21]
print(len(a))
print(a[3])
temp = []
merge(a, 0, len(a), temp)
print(a)

     得到的结果如下:

bubuko.com,布布扣      

这次学习中知道了如下:

1、python中没有++操作。

2、python中的数组其实就是list。

3、python中的除法/是浮点数,//是整数。

4、python中的递归调用限制了多少次。

5、python对数组的动态添加使用的是list中的append操作。

python中的归并排序,布布扣,bubuko.com

python中的归并排序

标签:归并排序   python   合并   算法   

原文地址:http://blog.csdn.net/qianligaoshan/article/details/25966407

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!