In: Computer Science
1.Instead of Build-Max-Heap, we could use Heap-Insert-Max to
build a tree with heap property. Write a pseudocode for that
procedure, also evaluate it’s time complexity.
2. How Insertion sort works on the following array
[16, 12, 3, 27, 9, 4, 5, 7]]
1)
Heap-Insert-Max(A, key)// A is the Max-Heap (array) and key is the value that is being inserted
{
A.size = A.size + 1;
i = A.size;
A[A.size] = key;
while(i > 0 and A[i] > A[Parent(i)])// Parent(i) returns the index of the parent node of node i ( celling(i /2) - 1, assuming array index strats from 0)
{
swap(A[i], A[Parent(i)]);
i = Parent(i);
}
}
The time compexity for the above pseudo code will be O(logn), where n is the number of nodes present in the Max-Heap. Basically in worst case the inserted node's value may have to traverse up to the root, which is nothing but the hegiht of the binary tree.
2) Insertion Sort works similarly like playing cards, we insert no.s one by one and keep on arranging them unitill all the elements have been inserted and eventually being sorted.
step i [12, 16, 3, 27, 9, 4, 5, 7] <12 is inseretd and compared with 16 as only one precceding data that is 16>
step ii [3, 12, 16, 27, 9, 4, 5, 7] <3 is inseretd and compared with two preceeeeding data 12, 16>
step iii [3, 12, 16, 27, 9, 4, 5, 7] <27 inserted and compared with 16 which is lesser than the inserted data so no further checking required.>
step iv [3, 9, 12, 16, 27, 4, 5, 7] <9 inserted....>
step v [3, 4, 9, 12, 16, 27, 5, 7] <4 inserted.....>
step vi [3, 4, 5, 9, 12, 16, 27, 7] <5 inserted....>
step vii [3, 4, 5, 7, 9, 12, 16, 27] <Finally, 7 inserted and compared with 27, 16, 12, 9, 5 and inserted or placed after 5>