a06-chap5-rand 算法导论 教学课件.pptVIP

  • 5
  • 0
  • 约1.71万字
  • 约 39页
  • 2018-01-25 发布于浙江
  • 举报
a06-chap5-rand 算法导论 教学课件

* * * * * * * * * * * * * * * * * 5.3.2 Randomly permuting an array (2) RANDOMIZE-IN-PLACE RANDOMIZE-IN-PLACE(A, n) for(i=1; i=n; i++) swap(A[i], A[RANDOM(i, n)] Correctness: Given a set of n elements, a k-permutation is a sequence containing k of the n elements. There are n!/(n-k)! possible k-permutations ? (给定 n 个元素,从其中任取 k 个元素进行排列,则有 n!/(n-k)! 种不同的 k-排列,或 k-置换 ?) Lemma RANDOMIZE-IN-PLACE computes a uniform random permutation. Proof Use a loop invariant: 1 2 3 … n A(1) A(2) A(3) … A(n) 1 2 3 … i1 … n A(i1) A(2) A(3) … A(1) … A(n) 1 2 3 … i2 … n A(i1) A(i2) A(3) … A(2) … A(n) * 5.3.2 Randomly permuting an array (2) RANDOMIZE-IN-PLACE RANDOMIZE-IN-PLACE(A, n) for(i=1; i=n; i++) swap(A[i], A[RANDOM(i, n)] Lemma RANDOMIZE-IN-PLACE computes a uniform random permutation. Proof Use a loop invariant: Loop invariant: Just prior to the ith iteration of the for loop, for each possible (i-1)-permutation, subarray A[1 .. i-1] contains this (i-1)-permutation with probability (n-i+1)!/n! ? (第 i 次迭代之前,对 (i-1)-置换,任意一个(i-1)-置换A[1 .. i-1]的概率为(n-i+1)!/n! ?) 1 2 3 … n A(1) A(2) A(3) … A(n) 1 2 3 … i1 … n A(i1) A(2) A(3) … A(1) … A(n) 1 2 3 … i2 … n A(i1) A(i2) A(3) … A(2) … A(n) * 5.3.2 Randomly permuting an array (2) RANDOMIZE-IN-PLACE Lemma RANDOMIZE-IN-PLACE computes a uniform random permutation. Proof Use a loop invariant: Loop invariant: A[1 .. i-1] contains each (i-1)-permutation with probability (n-i+1)!/n! . Initialization: Just before first iteration, i=1. Loop invariant says for each possible 0-permutation, subarray A[1 .. 0] contains this 0-permutation with probability n!/n!=1. A[1 .. 0] is an empty subarray, and a 0-permutation has no elements. So, A[1 .. 0] contains any 0-permutation with probability 1. (空集包含空置换的概率为1) RANDOMIZE-IN-PLACE(A, n) for(i=1; i=n; i++) swap(A[i], A[RANDOM(i, n)] 1 2 3 … n A(1) A(2) A(3) … A(n) 1 2 3 … i1 … n A(i1) A(2) A(3) … A(1) … A(n) 1 2 3 … i2 … n A(i1) A(i2) A(3) … A(2) … A(n) * 5.3.2 Randomly permuting an ar

文档评论(0)

1亿VIP精品文档

相关文档