C Program: Implementing decreaseKey in maximum Heap
8. DecreaseKey Extended Challenges
Write a C program that implements the decreaseKey operation in a maximum heap. Check the function by decreasing the key of a node and validating the heap property.
Sample Solution:
C Code:
Output:
Original Max Heap: 30 22 15 10 22 After Decrease Key at index 2 to 5: Max Heap: 30 22 5 10 22
Explanation:
In the exercise above,
- Struct Definition:
- struct MaxHeap: Represents a maximum heap using an array. It includes the array to store elements (array) and the current size of the heap (size).
- Utility Functions:
- swap: Swaps two elements in the heap.
- maxHeapify: Ensures a subtree rooted at a given index maintains the max-heap property.
- buildMaxHeap: Constructs a max heap from an array.
- createMaxHeap: Creates a max heap from an array and builds the max heap.
- decreaseKey: Decreases the key at a specified index in the max heap and adjusts the heap to maintain the max-heap property.
- printMaxHeap: Prints the elements in the max heap.
- Main Function:
- Initializes a max heap from an array.
- Prints the original max heap.
- Performs the decreaseKey operation on the max heap at index 2, reducing the key to 5.
- Prints the max heap after the decrease key operation.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to implement the decreaseKey operation in a max heap and adjust the heap efficiently after reducing a key's value.
- Write a C program to perform multiple decreaseKey operations on a max heap and count the number of swaps required to restore order.
- Write a C program to implement a robust decreaseKey function that prevents decreasing a key to a value higher than its current value.
- Write a C program to simulate repeated decreaseKey operations and verify that the heap property is maintained after each update.
C Programming Code Editor:
Previous: Merge two Heaps into a single max Heap.
Next: Finding Kth largest element with max Heap.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.