sortings in python
来源:互联网 发布:2017安全网络竞赛答案 编辑:程序博客网 时间:2024/05/29 17:59
这篇主要写几种sort的方法,后面还会持续更新。
1. heapsort
heap sort uses an array as a full tree to sort. time complexity is nlogn space is O(1) because it sorts in place.
it requires random access so we use array
everytime it sift down the largest element from the top.
code is as follow:
def siftdown(num,start,end): root=start while 2*root+1<=end: child=2*root+1 if child+1<=end and num[child]<num[child+1]: child+=1 if num[root]<num[child]: num[root],num[child]=num[child],num[root] root=child else: return
def heap(num): count=(len(num)-2)/2 start=count #stat is the largest parent while start>=0:# all nodes below the start index are in heap order siftdown(num,start,len(num)-1) start-=1# all nodes are in heap order print num for end in range(len(num)-1,0,-1): num[end],num[0]=num[0],num[end]# swap the root with the last element siftdown(num,0,end-1)# decrase the size of the heap so the previous max value will stay in its proper place print num
2. insertion sort:
O(n^2) O( 1)
每次都把第一个循环到的位置排列一遍
def insertion(num): for i in range(1,len(num)): j=i while j>0 and num[j]>num[j-1]: num[j],num[j-1]=num[j-1],num[j] j-=1 print num
3.quick sort
最差为O(n^2)
一般为nlogn
def quick(num,start,end): if end-start>0: pivot,left,right=num[start],start,end while left<=right: while num[left]<pivot: left+=1 while num[right]>pivot: right-=1 if left<=right: num[left],num[right]=num[right],num[left] left+=1 right-=1 quick(num,start,right) quick(num,left,end)def quicksort(num): quick(num,0,len(num)-1) def main(): num=[3,1,9,0,8,7,2,10] quicksort(num) print numif __name__=="__main__": main()
radix sort.
这种方法用的比较少,但是也是很重要的一种方法,时间复杂度取决于最大数的位数比如最大数是五位 的 那时间复杂度就是O(5*n)
def radix(num): RADIX=10 maxlength=False tmp,placement=-1,1 while not maxlength: maxlength=True bucket=[list() for _ in range(RADIX)] for i in num: tmp=i/placement bucket[tmp%RADIX].append(i) if maxlength and tmp>0: maxlength=False a=0 for i in range(RADIX): buck=bucket[i] for j in buck: num[a]=j a+=1 placement*=RADIX return numdef main(): num=[28,1,22,10,9,30,8] print radix(num)if __name__=="__main__": main()
0 0
- sortings in python
- URAL 1290. Sabotage (sortings)
- Codeforces 757C Felicity is Coming! hashing, sortings, strings
- codeforces-34B-B. Sale( C++ && greedy && sortings )
- [Python]Understand attribute in Python
- Text Processing in Python
- Algorithm in Python(1)
- Patterns in Python
- metaclass in python
- list in python
- Python in a Nutshell
- File Management in Python
- Text Processing in Python
- Python in a Nutshell
- source backup in python
- Python in a Nutshell
- Debugging Python in VIM
- install python in linux
- CXF中的类型转换
- LINUX下的消息队列实例解析(转)
- NYOJ 背包问题 106
- hdu 2476 区间dp
- [转载]STL:vector容器用法详解
- sortings in python
- Cocoa/Cocoa.h file not found
- innerText FF兼容性问题--摘抄
- iOS开发-xcode无法提交.a静态库文件的解决办法
- HDOJ 题目4006 The kth great number(优先队列水)
- java学习笔记,复习+总结(2)
- JS实现计时器(prototype)+表格排序
- iOS App分发
- Get Start StrangeIOC for Unity3D