常用排序算法比较
排序的稳定性和复杂度
不稳定:
选择排序(selection sort)— O(n2)
快速排序(quicksort)— O(nlogn) 平均时间, O(n2) 最坏情况; 对于大的、乱序串列一般认为是最快的已知排序
堆排序 (heapsort)— O(nlogn)
希尔排序 (shell sort)— O(nlogn)
基数排序(radix sort)— O(n·k); 需要 O(n) 额外存储空间 (K为特征个数)
稳定:
插入排序(insertion sort)— O(n2)
冒泡排序(bubble sort) — O(n2)
归并排序 (merge sort)— O(n log n); 需要 O(n) 额外存储空间
二叉树排序(Binary tree sort) — O(nlogn); 需要 O(n) 额外存储空间
计数排序 (counting sort) — O(n+k); 需要 O(n+k) 额外存储空间,k为序列中Max-Min+1
桶排序 (bucket sort)— O(n); 需要 O(k) 额外存储空间
排序python实现
1. 冒泡排序
def bublle_sort(l):
if l==[]:
return l
length=len(l)
for i in range(length):
for j in range(0,length-i-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
return l
2. 选择排序
def select_Sort(l):
if l==[]:
return l
length=len(l)
for i in range(length-1):
k=i
temp=l[i]
for j in range(i+1,length):
if temp>l[j]:
temp=l[j]
k=j
l[i],l[k]=l[k],l[i]
return l
3.插入排序
def Insert_sort(l):
if l==[]:
return l
length=len(l)
for i in range(1,length):
temp=l[i]
k=i
while k-1>=0 and temp<l[k-1]:
l[k]=l[k-1]
k-=1
l[k]=temp
return l
4.归并排序
def Merge(l1,l2):
l=[]
while l1!=[] and l2!=[]:
if l1[0]<l2[0]:
l.append(l1[0])
l1.pop(0)
else:
l.append(l2[0])
l2.pop(0)
if l1==[]:
l.extend(l2)
else:
l.extend(l1)
return l
def Merge_Sort(l):
length=len(l)
if length<=1:
return l
mid=length//2
l1=Merge_Sort(l[:mid])
l2 = Merge_Sort(l[mid:])
return Merge(l1,l2)
5.快速排序
def partion(l,i,j):
temp=l[i]
while i<j:
while i<j and l[j]>=temp: ####### 注意从右边开始容易一些
j-=1
if i<j:
l[i]=l[j]
while i<j and l[i]<=temp:
i+=1
if i<j: ######### 注意每个迭代后加判断条件
l[j]=l[i]
l[i]=temp
return i
def quick_sort(l,i,j):
if i>=j:
return l
mid=partion(l,i,j)
quick_sort(l,i,mid-1)
quick_sort(l,mid+1,j)
return l
6. 堆排序
def heap(l):
if l==[]:
return l
length=len(l)
start=length//2
while start>=0:
k=start
while 2*k+1<=length-1: ######### 先比较孩子节点比较好
temp=2*k+1
if 2*k+2<=length-1 and l[2*k+2]>l[2*k+1]:
temp=2*k+2
if l[k]<l[temp]:
l[k],l[temp]=l[temp],l[k]
k=temp
else:
break
start-=1
return l
def Heap_Sort(l):
out=[]
while l!=[]:
heap(l)
out.insert(0,l[0])
l[0]=l[-1]
l.pop(-1)
return out