归并排序与排序下界

Merge Sort

Basic idea of mergesort is divide-and-conquer paradigm.

  • Divide array into two halves.
  • Recursively sort each half.
  • Merge two sorted halves using two pointers.

In empirical analysis of merge sort, # compares is denoted by C(N)C(N), # array accesses is denoted by A(N)A(N). It is proven that C(N)≤Nlg⁡NC(N)\leq N\lg N and A(N)≤6Nlg⁡NA(N)\leq 6N\lg N for any array of size NN.

divide-and-conquer recurrence

Proposition. if D(N)=2D(N/2)+ND(N)=2D(N/2)+N for N>1N>1, with D(1)=0D(1)=0, then D(N)=Nlg⁡ND(N)=N\lg N.

We prove this by induction with base case N=1N=1 and inductive hypothesis D(N)=Nlg⁡ND(N)=N\lg N. The goal is to show that D(2N)=(2N)lg⁡(2N)D(2N)=(2N)\lg(2N).

D(2N)=2D(N)+2N=2Nlg⁡N+2N=2N(lg⁡(2N)−1)+2N=2Nlg⁡(2N) \begin{aligned} D(2N)&=2D(N)+2N \\ &= 2N\lg N+2N \\ &= 2N(\lg(2N) - 1)+2N \\ &= 2N\lg (2N) \end{aligned}

Mergesort uses extra space proportional to NN, which means it is NOT in-place.

Definition. A sorting algorithm is in-place if it uses ≤clog⁡N\leq c\log N extra memory.

Examples. Insertion sort, selection sort, shellsort.

Code Implementation

java
public class Merge {
	private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
    	assert isSorted(a, lo, mid);
    	assert isSorted(a, mid + 1, hi);
    
    	for (int k = lo; k <= hi; ++k)	aux[k] = a[k];
		int i = lo, j = mid + 1;
    	for (int k = lo; k <= hi; ++k) {
        	if (i > mid)                     a[k] = aux[j++];
        	else if (j > hi)                 a[k] = aux[i++];
        	else if (less(aux[j], aux[i]))   a[k] = aux[j++];
        	else                             a[k] = aux[i++];
    	}
    	assert isSorted(a, lo, hi);
    }

    // Recursive version
    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
        if (hi <= lo)	return;
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
        merge(a, aux, lo, mid, hi);
    }
    
    public static void sort(Comparable[] a) {
        aux = new Comparable[a.length];
        sort(a, aux, 0, a.length - 1);
    }
    
    // Non-recursive bottom-up version
    public static void sort(Comparable[] a) {
        int N = a.length;
        Comparable[] aux = new Comparable[N];
        for (int sz = 1; sz < N; sz <<= 1)
            for (int lo = 0; lo < N - sz; lo += sz+sz)
                merge(a, aux, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, N - 1));
    }
    
}

Practical Improvements

  • Use insertion sort for small subarrays.

    Mergesort has too much overhead for tiny subarrays. Cutoff to insertion sort for ≈7\approx 7 items.

    java
    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
    +   if (hi <= lo + CUTOFF - 1) {
    +   	Insertion.sort(a, lo, hi);
    +   	return;
    +   }
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
        merge(a, aux, lo, mid, hi);
    }
    
  • STOP if already sorted. (especially helpful for partially-ordered arrays.)

    java
    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
        if (hi <= lo)	return;
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
    +   if (!less(a[mid + 1], a[mid]))	return;
        merge(a, aux, lo, mid, hi);
    }
    
  • Eliminate the copy to the auxiliary array.

    Save time (not space) by switching the role of input and auxiliary array in each recursive call.

Complexity of Sorting

Computational complexity is a framework to study efficiency of algorithms for solving a particular problem XX. It consists of five components:

  • Model of computation. Allowable operations.
  • Cost model. Operation count(s).
  • Upper bound. Cost guarantee provided by some algorithms for XX.
  • Lower bound. Proven limit on cost guarantee by all algorithms for XX.
  • Optimal algorithm. Algorithm with best possible cost guarantee for XX.

We model the complexity of sorting problem as follows:

  • Model of computation. Decision trees.
  • Cost model. # compares.
  • Upper bound. ∼Nlg⁡N\sim N\lg N from mergesort.
  • Lower bound. ?
  • Optimal algorithm. ?

Decision Tree

Decision trees for compare-base sorting algorithms can access information only through compare.

comparable decision tree for 3 distinct items

Note that the height of the tree hh == the worst-case number of compares, and at least each leaf corresponds to a possible ordering of elements.

Lower Bound for Sorting

Proposition. Any compare-base sorting algorithm must use at least ∼Nlg⁡N\sim N\lg N compares in the worst case.

We prove this by establishing an inequality based on the number of leaves of decision tree.

  • Binary tree of height hh has at most 2h2^h leaves. # leaves ≤2h\leq 2^h.
  • N!N! different orderings →\to at least N!N! leaves. # leaves ≥N!\geq N!.
  • Worst case dictated by height hh of decision tree.

2h≥2^h\geq # leaves ≥N!⇒h≥lg⁡(N!)\geq N!\Rightarrow h\geq \lg(N!). According to the Stirling's formula, lg⁡(N!)∼Nlg⁡N\lg(N!)\sim N\lg N.

The lower bound of sorting problem is thus determined by h≥∼Nlg⁡Nh\geq \sim N\lg N.

We could see that the upper bound and the lower bound overlap each other (∼Nlg⁡N)(\sim N\lg N). Therefore, we could say that mergesort is an optimal algorithm for compare-base sorting problem.

Note that quicksort (stay tuned) is NOT optimal: it needs ∼12N2\sim\frac{1}{2}N^2 compares in the worst case.

CC BY-NC-SA 4.0
正在加载评论…