VOOZH about

URL: https://www.geeksforgeeks.org/dsa/heap-data-structure-implementation-in-swift/

⇱ Heap data structure implementation in swift - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Heap data structure implementation in swift

Last Updated : 28 Apr, 2025
  • A heap is a complete binary tree where each node satisfies the heap property. The heap property is different for different types of heaps but, in general, it means that each node has a value that is greater than or equal to (or less than or equal to) the values of its children nodes. 
  • Heaps are commonly used to implement priority queues, as they allow efficient insertion and removal of elements with the highest (or lowest) priority.

Types of Heap Data Structure:

  • Max Heap

Each node has a value that is greater than or equal to the values of its children nodes. The maximum value is always at the root of the heap.

  • Min Heap

Each node has a value that is less than or equal to the values of its children nodes. The minimum value is always at the root of the heap.

Below are the steps involved in the implementation of Max Heap:

  • Choose the type of heap: either min heap or max heap.
  • Create a class for the heap.
  • Create an array to hold the elements of the heap.
  • Implement the insert function to add new elements to the heap.
  • Implement the remove function to remove and return the top element from the heap.
  • Implement the peek function to return the top element of the heap without removing it.
  • Implement the isEmpty property to check if the heap is empty.

Here is the implementation of the max heap data structure in Swift:

Time complexity:

  • Insertion: O(log n)
  • Removal: O(log n)
  • Peek: O(1)

Auxiliary Space: O(n)

Comment
Article Tags: