C Program: Construct Max Heap from random and sorted arrays
2. Construct Max Heap Extended Challenges
Write a C program function that constructs a max heap from an array of elements. Test it with both random and sorted input arrays.
Sample Solution:
C Code:
Output:
Original Random Array: Array elements: 6 8 12 7 1 Max Heap from Random Array: Array elements: 12 8 6 7 1
Original Sorted Array: Array elements: 19 12 8 6 2 Max Heap from Sorted Array: Array elements: 19 12 8 6 2
Explanation:
In the exercise above,
- Header and definitions:
- Includes standard input/output and standard library headers.
- Defines a constant MAX_HEAP_SIZE for the maximum size of the heap.
- Swap function:
- Define a swap function to exchange the values of two variables.
- Heapify Down Function:
- Implement heapifyDown to maintain the max heap property after deleting an element.
- Compares the current node with its left and right children, swaps with the largest child if necessary, and recursively calls heapifyDown.
- Build Max Heap Function:
- Defines buildMaxHeap to construct a max heap from an array.
- Iterates from the last non-leaf node to the root, calling heapifyDown to ensure the max heap property is satisfied.
- Display Function:
- Defines display to print array elements.
- Main Function:
- Test with a random array:
- Initializes a random array.
- Displays the original random array.
- Builds a max heap from the random array.
- Displays the max heap from the random array.
- Test with a sorted array:
- Initializes a sorted array.
- Displays the original sorted array.
- Builds a max heap from the sorted array.
- Displays the max heap from the sorted array.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to construct a max heap from a partially sorted array and count the number of adjustments performed.
- Write a C program to build a max heap from an array using recursion rather than iterative loops.
- Write a C program to construct a max heap from an array containing duplicate elements while maintaining heap stability.
- Write a C program to construct a max heap from an array and validate the heap property at every level using level order traversal.
C Programming Code Editor:
Previous: Basic Heap Operations - Insert, Delete, Display.
Next: Construct Max Heap from random and sorted arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.