In: Computer Science
Remarks: In all algorithm, always explain how and why they work. If not by a proof, at least by a clear explanation. ALWAYS, analyze the running time complexity of your algorithms. In all algorithms, always try to get the fastest possible. A correct algorithm with slow running time may not get full credit. Do not write a program. Write pseudo codes or explain in words
Question 3: Give a data structure that implements a Min-Heap and the command M ax(S) that returns the maximum in the heap. Try and make the last operation as fast as possible.
Here's pseudo code for min heap implementation :
min_heapify(arr,int i,int n)
{
int lowest = i;
int l = 2*i+1;
int r = 2*i+2;
if(l < n && arr[l] < arr[lowest])
lowest = l;
if(r < n && arr[r] < arr[lowest])
lowest = r;
if(lowest != i)
{
swap(arr[lowest],arr[i]);
min_heapify(arr,lowest,n);
}
}
Build_min_heap(arr, int n)
{
for(int i = n/2-1;i >= 0; i--)
{
min_heapify(arr,i,n);
}
}
Now, come to getting max-element from min-heap.
Pseudo-code :
int findMaximumElement(int heap[], int n)
{
int maximumElement = heap[n / 2];
for (int i = 1 + n / 2; i < n; ++i)
maximumElement = max(maximumElement, heap[i]);
return maximumElement;
}
Like, if this helped :)