Divide and Conquer.(Merge Sort) by sixleaves

<!doctype html>



algo-C1-Introduction css

Merge Sort:

一.Motivation and Example

why study merge sort?

  • Good introduction to divide & conquer
  • Calibrate your preparation
  • Motivates guiding principles for algorithm analysis(worst-case and asymptotic analysis)
  • Analysis generalizes to 「Master Method"

The Sorting Problem

Input: array of n numbers, unsorted. (5 4 1 8 7 2 6 3)web

Output: same numbers, sorted in increasing order (1 … 8)app

Example:

QQ20150811-1

二.Pseudocode:

  • recursively sort 1st half of input array
  • recursively sort 2nd half of input array
  • merge two sorted sublists into one[ ignores base cases]

Pseudocode for Merge:

QQ20150811-2

Merge Sort Running Time:

Key Question: running time of MergeSort on array of n numbers?ide

[Running time ~ #of mines of code executed ]ui

Running Time of Merge:

running time of merge on array of m numbers is <= 4m + 2 <= 6m(since m >= 1)this

Running Time of Merge Sort

Claim: MergeSort requires <= spa

6nlog2n+6n

operations for sort n numberscode

Recall:

log2n

of times you divide by 2 until you get a number that drops below oneorm

So if you plug in 32 you got to divide five time by two get down to one.

三.Analysis

Claim:

For every Input array of n numbers, Merge Sort produces a sorted output array and uses at most 6nlog_2n + 6n operations.

Proof of calim (assuming n = power of 2):

Question1:

how many levels does this recursion tree have.===>

beacause: {level0, level1……. level(log2n)} === > (log_2n - 0) + 1 ===>

log2n+1

Question2

at each level j = 0,1 ,2 , log_2n, there are 2^j subproblems, each of size n / 2^j.

第二個的緣由很簡單, 這顆遞歸樹的第j層的子問題有 2^j 個, 例如第0層是1個, 第1層是兩個, 由此類推, 因此每一個的大小都是n / 2^j.

Proof of claim

第j層總的合併程序中所含有的指令次數是 <= 2 ^j * 6(n / 2^j) = 6n.也就是所每一層的合併程序內部所作的指令次數都是固定的, 爲6n次, 因此對於這課共有log2n + 1個層的數, 總的操做次數爲6n( log2n + 1) = 6nlog_2n + 6n.

相關文章
相關標籤/搜索