Heap in C - GeeksforGeeks (2024)

Last Updated : 05 Jun, 2024

Improve

A heap is a type of tree data structure where each node is either greater than or equal to or is less than or equal to the values of its children. Depending on this, there are two types of heaps:

  • Min Heap: Each node is less than or equal to the value of its child subtrees.
  • Max Heap: Each node is greater than or equal to the value of its child subtrees.

Apart from this, heap is also a complete tree. It means that all the before the last level have all its children nodes and in the last level, all the children will be filled from left to right.

In this article, we will learn how to implement the heap data structure in C along with its basic operations. We will take binary heap for example. For k-ary heap, please refer to this article – K-ary Heap Data Structure

Implementation of Heap in C

In C, heaps are typically stored in arrays. This makes them faster to access and modify elements. And due to its completeness, we can easily find the index of the child and parents nodes. Here is how to find child and parent nodes of an element at index i in the array:

  • Left child: 2 * i + 1
  • Right child: 2 * i + 2
  • Parent: (i – 1) / 2

All the values are assuming the index starts from 0.

Heap Representation in C

We can represent heap directly as an array but we will then have to keep the track of the size in another variable and will have to pass this variable as another argument to heap functions. To simplify it, we can create a structure with array and the size variable in it to represent the heap in C.

typedef struct heap {
int size;
int capacity;
int* arr;
} Heap;

Heap Operations Implementation in C

There are seven basic operations that are needed to work with heap data structure:

Operation NameDescriptionTime ComplexitySpace Complexity
InsertAdds a new element to the heap and maintains the heap property.

O(log n)

O(1)

Extract Min/MaxRemoves and returns the minimum/maximum element from the heap.

O(log n)

O(1)

PeekReturns the minimum/maximum element without removing it.

O(1)

O(1)

HeapifyReorganizes a subtree for the given node to ensure the heap property holds

O(log n)

O(1)

DeleteRemoves a specific element from the heap.

O(log n)

O(1)

Increase/Decrease KeyChanges the value of an existing element in the heap.

O(log n)

O(1)

Build HeapConverts an array into a proper min or max heap.

O(n)

O(1)

Heapify Implementation in C

Heapify function is implemented with the function signature: heapify(Heap* heap, int i) where, heap is the pointer to Heap and i is the index on which heapify is called.

  1. Check if the left child exists.
  2. If the left child exists and is greater than the current largest node, mark it as largest.
  3. Check if the right child exists.
  4. If the right child exists and is greater than the current largest node, mark it as largest
  5. If the largest node is not the root node, swap the root node with the largest node using theswapfunction.
  6. Apply heapify operation to the affected subtree.

Build Heap Implementation in C

  1. Get the number of elements in the heap.
  2. Identify the starting point for heapification. The function identifies the last non-leaf node in the heap, which is the parent of the last element. This is calculated as(n – 1) / 2.
  3. The function then enters a loop that starts from the last non-leaf node and goes up to the root node. Inside the loop, it callsheapify(heap, i)to ensure that the subtree rooted atiis a max heap heapifying all the levels.

Insert Key Implementation in C

  1. Check if the max heap is full. If it is, print “MaxHeap overflow” and return from the function.
  2. If the heap is not full, increase the size of the heapby 1.
  3. Insert the new value at the end of the heap.
  4. If the newly inserted value is greater than its parent, the max heap property is violated. To fix this, the function enters a loop that continues untiliis not 0 and the parent ofiis less thani. Inside the loop, it swaps the value atiwith its parent and then updatesito be the index of the parent.

Extract Min/Max Implementation in C

  1. Check if the heap is empty. Ifit is empty, returnINT_MIN/INT_MAXas an indication that the heap is empty.
  2. Else, store the root value (maximum/minimum value) intemp, replace the root with the last element in the heap, and decrementheap sizeby 1.
  3. Call Heapify(Heap, 0)to ensure that the new root is the maximum element in the heap.
  4. Finally, returntemp, which is the extracted maximum value.

Delete Key Implementation in C

  1. Check if the index is valid. If the index is invalid, print “Invalid index” and return from the function.
  2. If the element to be deleted is the last element in the heap, simply decrementheap sizeby 1 and return from the function.
  3. Move the last element to the index of the element to be deleted.
  4. Reduce the size of the heap.
  5. Callheapify(heap, index)to ensure that the subtree rooted at the given index is a heap.

Increase Key Implementation in C

  1. Check if the index is valid and new value is greater. If it is, print “Invalid index or new value is not greater” and return from the function.
  2. If the index is valid and the new value is greater, update the value at the given index to the new value.
  3. If the updated value is greater than its parent, the max heap property is violated. To fix this, the function enters a loop that continues untilindexis not 0 and the parent ofindexis less thanindex. Inside the loop, it swaps the value atindexwith its parent and then updatesindexto be the index of the parent.

The decrease key for min heap will also be implemented using the same algorithm.

C Program to Implement Heap Data Structure

C
#include <limits.h>#include <stdio.h>#include <stdlib.h>// Structure to represent a Heap (previously MaxHeap)typedef struct Heap { int* array; int size; int capacity;} Heap;// Function to create a heapHeap* createHeap(int capacity){ Heap* heap = (Heap*)malloc(sizeof(Heap)); heap->size = 0; heap->capacity = capacity; heap->array = (int*)malloc(capacity * sizeof(int)); return heap;}// Function to swap two integersvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;}// Function to heapify the node at index ivoid heapify(Heap* heap, int i){ int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < heap->size && heap->array[left] > heap->array[largest]) largest = left; if (right < heap->size && heap->array[right] > heap->array[largest]) largest = right; if (largest != i) { swap(&heap->array[i], &heap->array[largest]); heapify(heap, largest); }}// Function to build a max heap from an existing arrayvoid buildHeap(Heap* heap){ int n = heap->size; // Get the number of elements in the // heap // Start from the last non-leaf node (parent of the last // leaf) and heapify all levels in reverse order for (int i = (n - 1) / 2; i >= 0; i--) heapify(heap, i);}// Function to increase the value at a given indexvoid increaseKey(Heap* heap, int index, int newValue){ if (index >= heap->size || heap->array[index] >= newValue) { printf( "Invalid index or new value is not greater\n"); return; } heap->array[index] = newValue; while (index != 0 && heap->array[(index - 1) / 2] < heap->array[index]) { swap(&heap->array[index], &heap->array[(index - 1) / 2]); index = (index - 1) / 2; }}// Function to insert a new value into the heapvoid insertHeap(Heap* heap, int value){ if (heap->size == heap->capacity) { printf("Heap overflow\n"); return; } heap->size++; int i = heap->size - 1; heap->array[i] = value; // Fix the heap property if it is violated while (i != 0 && heap->array[(i - 1) / 2] < heap->array[i]) { swap(&heap->array[i], &heap->array[(i - 1) / 2]); i = (i - 1) / 2; }}// Function to extract the root (maximum element)int extractMax(Heap* heap){ if (heap->size <= 0) return INT_MIN; if (heap->size == 1) { heap->size--; return heap->array[0]; } // Store the maximum value, and remove it int root = heap->array[0]; heap->array[0] = heap->array[heap->size - 1]; heap->size--; heapify(heap, 0); return root;}// Function to print the heapvoid printHeap(Heap* heap){ for (int i = 0; i < heap->size; ++i) printf("%d ", heap->array[i]); printf("\n");}// Function to delete an element at a given indexvoid deleteKey(Heap* heap, int index){ if (index >= heap->size) { printf("Invalid index\n"); return; } // If the element to be deleted is the last element, // simply reduce size if (index == heap->size - 1) { heap->size--; return; } // Move the last element to the index of the element to // be deleted heap->array[index] = heap->array[heap->size - 1]; heap->size--; // Heapify down to maintain heap property heapify(heap, index);}int main(){ Heap* heap = createHeap(10); insertHeap(heap, 3); insertMaxHeap(maxHeap, 2); insertMaxHeap(maxHeap, 15); insertMaxHeap(maxHeap, 5); insertMaxHeap(maxHeap, 4); insertMaxHeap(maxHeap, 45); printf("Max Heap array: "); printHeap(maxHeap); printf("Extracted max value: %d\n", extractMax(maxHeap)); printf("Max Heap array after extraction: "); printHeap(maxHeap); free(maxHeap->array); free(maxHeap); return 0;}

Output

Max Heap array: 45 5 15 2 4 3 Extracted max value: 45Max Heap array after extraction: 15 5 3 2 4 

The min heap can be easily implemented using the same algorithms. We will just need to change the comparison operator to less than (<).



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Heap in C - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 5999

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.