算法导论第七章学习笔记

来源:互联网 发布:孙越演的网络剧 编辑:程序博客网 时间:2024/06/06 00:53

Randomized quicksort

Idea: Partition around a random element.

  • Running time is independent of the input order.
  • No assumptions need to be made about the input distribution.
  • No specific input elicits the worst-case behavior.
  • The worst case is determined only by the output of a random-number generator.

Expected running time

Quicksort takes Θ(n2) time: when partitioning is unbalanced. if, in each level of recursion, the split induced by RANDOMIZED-PARTITION puts any constant fraction of the elements on one side of the partition, then the recursion tree has depth Θ(lg n), and O(n) work is performed at each level. Even if we add new levels with the most unbalanced split possible between these levels, the total time remains O(n lg n).

Randomized quicksort analysis

Let T(n) = the random variable for the running time of randomized quicksort on an input of size n, assuming random numbers are independent. For k = 0, 1, …, n–1, define the indicatorrandom variable

Xk = 1 if PARTITION generates a k : nk–1 split,

Xk = 0 otherwise.

E[Xk] = Pr{Xk = 1} = 1/n,

since all splits are equally likely, assuming elements are distinct.

Take expectations of both sides, and use Linearity of expectation.

Independence of Xk from other random choices. and E[Xk] = 1/n .

(The k = 0, 1 terms can be absorbed in the Θ(n).)

Hairy recurrence

Prove: E[T(n)] ≤ anlg n for constant a > 0 .

Choose a large enough so that anlg n dominates E[T(n)] for sufficiently small n ≥ 2.

Substitution method

Quicksort in practice

Quicksort is a great general-purpose sorting algorithm.

Quicksort is typically over twice as fast as merge sort.

Quicksort can benefit substantially from code tuning.

Quicksort behaves well even with caching and virtual memory.