A Docxweek10
A Docxweek10
Recurrence relation:
T(n) = 2*T(n/2) + O(n)
Unrolling:
1st unrolling: T(n) = 2*T(n/2) + O(n)
2nd unrolling:
T(n) = 2*(2*T(n/4) + O(n/2)) + O(n)
T(n) = 2*2*T(n/4) + 2*O(n/2) + O(n)
3rd unrolling:
T(n) = 2*2*(2*T(n/8) + O(n/4)) + 2*O(n/2) + O(n)
T(n) = 2*2*2*T(n/8) + 2*2*O(n/4) + 2*O(n/2) + O(n)
….
Ith unrolling:
T(n) = 2i * T(n/2i) + i * O(n)
Question 3
A = [2,3,4,3,3]
a) X is a majority element:
Count(x) in the whole > n/2
Count(x) in first half > n/4 OR Count(x) in second half > n/4
b)
Def check_majority(A, x):
count = 0
for e in A:
If x == e:
count += 1
return count > len(A)/2
Def find_majority(A):
If len(A) == 1:
Return A[0]
Mid = len(A)/2
Half1 = find_majority(A[0:mid])
Half2 = find_majority(A[mid:len(A)])
If Half1 != None and check_majority(A, Half1):
Return Half1
If Half2 != None and check_majority(A, Half2):
Return Half2
Return None
[2,3,2,3]
d) Same as problem 2
Question 4.
Merge sort removes inversions when a value is selected from the right half.
The number of inversions removed is the number of elements remaining in the
left half
def merge_sort(S):
# base case if |S| < 2 then
return S
mid ← ⌊|S|/2⌋
# divide
Question 5.
- Start in the centre
Question 6.
Time complexity:
The number of elements in the list after each pass will decrease by at least
half, since at least one value is removed for every 2 values.
Therefore the number of iterations will be:
n + n/2 + n/4 + n/8 + n/16 + …. 2*n = O(n)
ie,
T(n) = T(n/2) + O(n)
Solves to O(n)
On each iteration, O(1) to compare adjacent elements, and O(1) to remove
from the middle of a doubly linked list (we know the node position).
Alternative approach:
- Keep a candidate majority element, initially set to the first value
- Keep a counter initially zero
- Iterate through the list, check if the element is equal to the candidate, if
it is, increase the counter, otherwise decrease the counter. If the
counter falls below 0, set the current element to be the new candidate
and reset counter to 0
- At the end, check if the candidate is a majority in the whole list. If it is,
return it.
[4,4,4,7,3]