Divide and Conquer
Last updated
Last updated
Master theorem. Let a ≥ 1, b ≥ 2, and c ≥ 0 and suppose that T(n) is a function on the non-negative integers that satisfies the recurrence
with T(0) = 0 and T(1) = Θ(1), where n / b means either ⎣n / b⎦ or ⎡n / b⎤. Then,
If , then . (Combining cost more than subproblem)
If , then .
If , then . (Combining cost less than subproblem)
For a sorted array, find the given item
find the mid item, compare it to the target
less than goes to left subarray;
bigger than goes to right subarray;
continue util find it at mid or find none
After loop, and will return -1
Divide and conquer happens at the same time, there is no combining, so
divide
becuase we only consider one subproblem
Given an array a sorted nums
and an element target
, find the index such that all the elements to the left are smaller than target
, all the elements to the right and the current element are bigger than or equal to target
.
The index returned can be 0 or len(nums)
Given an array a sorted nums
and an element target
, find the index such that all the elements to the left are smaller than or equal to target
, all the elements to the right and the current element are bigger than target
.
The index returned can be 0 or len(nums)
Proof:
Add them together, proof is concluded.
Find the middle item, compare it to the target, with
If less than, consider right subarray by
If bigger than or equal to, consider the left subarray; however since this current element can be the index we are looking for, so we include the
After all scanning, return either lo or hi since
Find the middle item, compare it to the target, with
If less than or equal to, consider right subarray; however since this current element can be the index we are looking for, so we include the
If bigger than, consider the left subarray
After all scanning, return either lo or hi since
Given an array of distinct elements the probability that and are compared during randomized quicksort is
Hint: think about the subarray , choosing anything other than or will never compare and anymore, because they are split into different branches of the chosen pivot element. To chose either or the probabilty is .
Step 1, n == 2: and will be definitely compared, and the probability is 1.
Step 2, :
To choose either or is with prob of
To choose one outside is with prob of , then and will be partitioned into the same branch of the chosen pivot element. By induction, that probability of them get compared within that subarray is