这篇主要写几种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 num
if __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 num
def main():
num=[28,1,22,10,9,30,8]
print radix(num)
if __name__=="__main__":
main()