Skip to content

Sorting

  • 效率 | Efficiency

  • 原地性 | In Place

  • 稳定性 | Stability

A sorting algorithm is stable if elements with equal elements are left in the same order as they occur in the input.

A stable algorithm can be suitable for Multiple targets.

Insertion Sort

Shell Sort

ht = N/2, hk = hk+1/2.

with Worst case O(N2)

Now we have better selection with worst case O(N7/6) with

hk={94i92i+1,imod2==04i+162i+1,imod2==1

Heap Sort

Merge Sort

Quick Sort

  • Picking the Pivot

  • Partition

Partition
Partition(A, p, q)
    x=A[p]
    i=p+1
    j=q
    while(i!=j)
        while(A[j]>=x && i<j)
            j-- // put larger element in place 
        while(A[i]<=x && i<j)
            i++ // put smaller element in place 
        if(i<j)
            swap(A[i], A[j])
    swap(A[p], A[i])
Another Partition
Partition(A, p, q)
    x=A[p]
    i=p
    for j=p+1 to q:
        if(A[j]<=x)
            i=i+1
            swap(A[i],A[j])
    A[p]=A[i]
    return i
QuickSort
QuickSort(A,p,q)
    if(p<q)
        r=partition(A,p,q)
        QuickSort(A,p,r-1)
        QuickSort(A,r+1,q)

Time cost:

  • Ordered sequence
T(n)=T(1)+T(n1)+Θ(n)
  • Best sequence
T(n)=2T(n/2)+Θ(n)
  • not Bad or Good

Every Partition gives 1:9 sequence

Randomize pivot

Text Only
Randomized_Partition(A,p,q)
    i=random(p,q)
    swap(A[p],A[i])
    return Partition(A,p,q)
Text Only
randomized_quicksort(A,p,q)
    if(p<q)
        r=randomized_Partition(A,p,q+1)
        randomized_quicksort(A,p,r-1)
        randomized_quicksort(A,r+1,q)

Some Details

  • Consider repetitive elements
Text Only
Hoore_Partition(A,p,q)
    x=A[p]
    i=p, j=q+1
    while(1):
        do:
            j=j-1
        until(A[j]<=x)
        do:
            i=i+1
        until(A[i]>=x)
        if(i<j)
            swap(A[i],A[j])
        else
            swap(A[p],A[j])
            return j

A General Lower Bound for Sorting

Efficiency of sorting with comparing

The best efficiency of sorting based on comparing is Θ(nlogn)

left tree denotes true, right tree denotes false, every leaf node represents a result of sorting. We have n! nodes. And let h denote the height of the decision tree. we have

n!2h

"=" holds for complete binary decision tree. So

hlogn!log(n/e)n=Ω(nlogn)