Python 快速排序 堆排序——Python实现一些算法持续更新

来源:互联网 发布:openstack入门 知乎 编辑:程序博客网 时间:2024/04/29 13:24

大四了为了追我喜欢的姑娘,我想找份北京的工作,可实力略弱,但我会学,现在恶补算法,看了好多大牛的Blog,自己也应该有点产出,回馈大家,让自由和共享继续

快速排序:

<span style="color:#660000;">#-*-coding:utf-8-*-'''Quick Sort write by miss chu '''def quickSort(L,start,end):if start>=end:returnstart_=startend_=endpivot = L[start_]while start_<end_:while (start_<end_)and(L[end_]>=pivot):end_-=1if start_<end_:L[start_] = L[end_]start_+=1while (start_<end_)and(L[start_]<=pivot):start_+=1if start_<end_:L[end_] = L[start_]end_-=1L[start_] = pivotquickSort(L,start,start_-1)quickSort(L,start_+1,end)def swap(a,b):return b,aif __name__ == '__main__':print "Quick Sort"numlist = [5,9,2,4,1,7,3,6,8]quickSort(numlist,0,len(numlist)-1)print numlist</span>
堆排序:

#-*-conding:utf-8-*-"""Heap Sort by nianchu!"""def getLeftChild(i):return 2*i+1def buildHeap(L,i,len): #At this place we build a big heapwhile i<=len and getLeftChild(i)<=len:temp = L[i]child = getLeftChild(i)if child+1<=len and L[child+1]>L[child] :child+=1if L[child]>temp:L[i],L[child]=L[child],L[i]i=childdef returnBigHeap(L,len): #And now we make a big heap and then we make L a list whos value is more and moer biggeri = len/2while i>=0:buildHeap(L,i,len)i-=1j=lenwhile j>0:L[0],L[j] = L[j],L[0]j-=1buildHeap(L,0,j)if __name__ == '__main__':print "Heap Sort"l = [1,5,6,9,4,2,3,7,8]returnBigHeap(l,len(l)-1)print l

归并排序:

<span style="font-size:14px;">#-*-coding:utf-8-*-def merge(list):if len(list)<=1:return listmid=len(list)/2left=merge(list[:mid])right=merge(list[mid:])return mergeCore(left,right)def mergeCore(left,right):result=[]i=0j=0while i<len(left) and j<len(right):if left[i]<right[j]:result.append(left[i])i+=1else:result.append(right[j])j+=1result+=left[i:]result+=right[j:]return resultif __name__ == '__main__':list = [1,4,3,2,7,6,5,9,8,0]print merge(list)#print list</span>


亡羊补牢为时未晚,学习算法学习coding学安全不是一朝一夕的事情,持之以恒。

期待一份北京的工作

————本篇Blog会持续更新,如有批评建议欢迎指正,共同进步

0 0