最近在看麻省的《算法导论》公开课(以网易公开课为准),准备就学习体会和相关的编程练习写一篇连载。
简要说一下,语言希望能够都使用python。大多数的算法练习资料都是用C/C++,而且好多公司也要求是C/C++的实现。前段时间一直在用PYTHON,而且也仔细看了些书。
我觉得python还是很不错的语言,语法简要,风格优美。
另外一方面,python的适用性很强,你可以用它开发客户端,也可以写服务端。有时候我常常为自己学习的语言混杂(js、C#、C/C++、php、bash等)而苦恼,我现在希望能够只专注于python的应用。而把精力更多放在一些更深入的内容中,例如机器学习和数据处理等的研究。
---- 引言
第一课主要是讲排序算法和算法性能的一些评估方法和标记。
由于前期没有做很好的准备,笔记不多,现在只给出插入排序和归并排序的算法实现。
1.开发和测试环境说明如下:
程序语言:python 2.7
IDE:ulipad(如果有朋友在安装ulipad出现问题时可以联系我,我之前在win7下用ulipad使用没有,换成xp后竟然安装碰到点问题,索性解决了。)
2.关键笔记
插入排序的时间复杂度是O(n*n),
归并排序的时间复杂度是O(n lg n)。
3. 算法实现
#!/usr/bin/env python
#coding:utf-8
import sys
"""
This file provide the program of insertion sort
and merge sort
@author:xiaoyongpeng
@date:2012-11-28
"""
def InsertSort(numList):
len_list = len(numList)
if not len(numList):
print "list must not be null."
return None
for j in range(1,len_list):
temp = numList[j]
i = j-1
while i >=0 and numList[i+1] < numList[i]:
numList[i+1] = numList[i]
numList[i] = temp
i -= 1
return numList
"""
Augrment:
num : must be float type
"""
def Ceil(num):
if float(num) - int(num) > 0:
return int(num)+1
else:
return int(num)
def MergeSort(numList):
if len(numList) <= 1:
return numList
else:
half = float(len(numList))/2
half = Ceil(half)
numList_first = numList[:half]
numList_second = numList[half:]
numList_last = []
#print "[%d] %s,%s" % (half,numList_first,numList_second),
numList_first = MergeSort(numList_first)
numList_second = MergeSort(numList_second)
while numList_first or numList_second:
if numList_first and numList_second:
if numList_first[0] <= numList_second[0]:
numList_last.append(numList_first.pop(0))
else:
numList_last.append(numList_second.pop(0))
else:
numList_last += numList_first if numList_first \
else numList_second
break
#print numList_last
return numList_last
if __name__ == '__main__':
num_list = []
input_num = raw_input("please input an numList \
and seperated by ',':")
if input_num:
temp_list = input_num.strip().split(',')
try:
num_list = [int(x) for x in temp_list]
except ValueError,args:
print str(args)
sys.exit(0)
CMD = {'i':InsertSort,'m':MergeSort}
printInfo = """Please choose your command:
(i)nsertion sort
(m)erge sort
(q)uit
"""
while True:
cmd_input = raw_input(printInfo).strip().lower()
if not cmd_input in 'imq':
print "Please reinput your command."
continue
elif cmd_input == 'q':
print 'quit now.'
break
else:
#注意列表的赋值操作默认是使用浅拷贝方式
#例如num_last = num_list指向的引用的对象是一致的
num_last = [x for x in num_list]
num_last = CMD[cmd_input](num_last)
print "First:",num_list
print "Last:",num_last