Professional Documents
Culture Documents
A) Illustrate The Operation of The MAKEHEAP Algorithm To Build A Max-Heap. (Show Your Steps)
A) Illustrate The Operation of The MAKEHEAP Algorithm To Build A Max-Heap. (Show Your Steps)
a) Illustrate the operation of the MAKEHEAP algorithm to build a max-heap. (show your steps)
1)
7 2
1 9 8 6
7 2
4 9 8 6
3) sift-down 2:
7 8
4 9 2 6
1
4) sift-down 7:
9 8
4 7 2 6
5) sift-down 3:
7 8
4 3 2 6
7 1
4 3 2 6
7 6
4 3 2 1
7 6
4 3 2 1
20
2) Sift-up 20:
20
9 6
7 3 2 1
Question 2. (15 points) Give an algorithm to merge two heaps into one heap. What is the time
complexity of your algorithm? (Your algorithm must be O(n) where n = n1 + n2 and n1 is the size
of heap 1 and n2 is the size of heap 2)
Input: Heap1 [1..n], Heap2 [1..n], i, n, Arr3.
Output: heap3[1..(heap1.size+heap2.size)]
i = 1, n = 1
While i<=heap1.length
o Arr3[i] = heap1[i]
o i = i+1
While n<= heap2.length
o Arr3[i] = heap2[n]
o n++
o i++
Heap3 = makeAHeap(Arr3);
The time complexity is O(n+m) for looping both heaps, and O(n) for makeAheap. Hence, the
time complexity is O(n)
Question 3. (10 points) Solve the following recurrence relations and express them in bigtheta-
notation:
i. f(n) = 6f(n – 1) for n >= 1; f(0) = 5;
f(n) = 6f(n-1)
f(n) = 6 * 6f(n-2)
f(n) = 6 * … *6f(0)
f(n) = 6 n∗5
Time complexity = Big-Theta(6 n)
n n n
( )
f( 2 ) = 2f( 3 ) + 2 log 2
2 2 2
n
2
f(n) = 2
logn
( ( ))
f ( 1 ) +logn n log
n
logn−1
2
f(n) = nf(1) + logn( n log ( 2 ))
f(n) = n + log(2)nlogn
Time complexity = Big-theta(nlogn)
Question 5. (10 points) Use Master’s theorem to solve the following recurrence relations and
express it in Big-theta-notation:
i. f(n) = 4f(n/2) + n2
a = 4, b = 2, g(n) = n2
n log 4 =n2
2
f(n) = Θ ( n2 logn )
ii. f(n) = 𝑛.
a=√ 2 ,b=2 , g n =√ n
( )
1
log √ 2
n 2
= n2 = √ n
Since g ( n ) is also √ n. By case 2:
f(n) = Θ( √ n logn)
Question 6. (10 points) Illustrate the operation of Algorithm radixsort on the following sequence
of eight numbers: 4567, 2463, 6523, 7461, 4251, 3241, 6492, 7563. (show your steps)
Question 9. (20 points) Let A[1..n] be a sorted array of n integers, and x an integer. Design an O(n)
time recursive algorithm to determine whether there are two elements in A, if any, whose sum is
exactly x. Show that the running time of the algorithm is O(n) in the worst case.
Input: Arr, x, startIndex = 1, finalIndex = n
Output: true or false.
matchX(Arr, x, startIndex, finalIndex)
if startIndex == finalIndex
o return false
if Arr[startIndex] + Arr[finalIndex] == x
o return true
if Arr[startIndex] + Arr[finalIndex] > x
o return matchX(Arr, x, startIndex, finalIndex-1)
return matchX(Arr, x, startIndex+1, finalIndex)
The time complexity in the worst case will be when the sum is not in the array.
The function matchX will be called n times, hence the time complexity is Θ(n).