## [算法导论]排序算法及主定理

冒泡排序 O(n2) 内部排序,稳定排序

for i = n to 2

for j = 1 to i-1

if  a[j]>a[j+1]

do exchange a[j] and a[j+1]

end

end

插入排序 O(N2) 内部排序 虽然复杂度较高,但实际应用中效果较好,小规模适合,最优O(N) 稳定排序

for i = 2 to n

d=a[i]

j = i-1

while j>=1 and a[j]>a[j+1]

do a[j+1]=a[j];

a[j]=d;

end

归并排序 O(NlogN) 外部排序,但复杂度低,最后算法的逼近 稳定排序

merge(a,p,q,r)

{

i=q-p+2

j=r-q+1

create b[1...i-1]=a[p...q],c[1...j-1]=a[q+1...r]

b[i]=+∞ c[j]=+∞

m=n=1

for s=p to r

if b[m]<c[n]

do a[s]=b[m]

m++ s++

else do a[s]=c[n]

n++ s++

end

end

}

merge_sort(a,x,y)

{

merge_sort(a,x,(x+y)/2)

merge_sort(a,(x+y)/2+1,y)

merge(a,x,(x+y)/2,y)

}

max_heap(a,r)

{

i=r*2

j=r*2+1

large=r

if a[i]>a[large] do large=i

if a[j]>a[large] do large=j

if large!=r do exchange a[r] and a[large]

if large<heap_size/2 do max_heap(a,large)

}

build_max_heap(a,n)

{

for i= n/2 to 1 do max_heap(a,i)

}

heap_sort(a,n)

{

heap_size=n

build_max_heap(a,n)

while heap_size>=1

do exchange a[1] and a[heap_size]

heap_size--

max_heap(a,1);

}

p=partition(a,r)

{

d=a[r]

i=0;

for j=1 to r-1

if a[j]<a[r]

do i++

exchange a[i] and a[j]

end

p=i+1

exchange a[r] and a[p]

}

quick_sort(a,n)

{

p=partition(a,n)

quick_sort(a,p-1)

quick_sort(a,p+1)

}

T(n)=aT(n/b)+f(nc)

1.  log(b)a<c  则O(nc)

2.  log(b)a=c 则O(nclogn)

3.  log(b)a>c 则O(n(log(b)a))

posted on 2011-09-09 00:01  伪君  阅读(658)  评论(0编辑  收藏  举报