Open In App

Heap data structure implementation in swift

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
  • 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:

Swift




// Swift code for the above approach:
class MaxHeap<T: Comparable> {
    var heap: [T] = []
      
    // Insert a new element into the heap
    func insert(_ element: T) {
        heap.append(element)
        var currentIndex = heap.count - 1
          
        // Bubble up the element until the
        // heap property is restored
        while currentIndex > 0 && heap[currentIndex] > heap[(currentIndex-1)/2] {
            heap.swapAt(currentIndex, (currentIndex-1)/2)
            currentIndex = (currentIndex-1)/2
        }
    }
      
    // Remove and return the top
    // element of the heap
    func remove() -> T? {
        guard !heap.isEmpty else {
            return nil
        }
          
        let topElement = heap[0]
          
        if heap.count == 1 {
            heap.removeFirst()
        } else {
            
            // Replace the top element 
            // with the last element in
            // the heap
            heap[0] = heap.removeLast()
            var currentIndex = 0
              
            // Bubble down the element until
            // the heap property is restored
            while true {
                let leftChildIndex = 2*currentIndex+1
                let rightChildIndex = 2*currentIndex+2
                  
                // Determine the index of
                // the larger child
                var maxIndex = currentIndex
                if leftChildIndex < heap.count && heap[leftChildIndex] > heap[maxIndex] {
                    maxIndex = leftChildIndex
                }
                if rightChildIndex < heap.count && heap[rightChildIndex] > heap[maxIndex] {
                    maxIndex = rightChildIndex
                }
                  
                // If the heap property is 
                // restored, break out of the loop
                if maxIndex == currentIndex {
                    break
                }
                  
                // Otherwise, swap the current
                // element with its larger child
                heap.swapAt(currentIndex, maxIndex)
                currentIndex = maxIndex
            }
        }
          
        return topElement
    }
      
    // Get the top element of the
    // heap without removing it
    func peek() -> T? {
        return heap.first
    }
      
    // Check if the heap is empty
    var isEmpty: Bool {
        return heap.isEmpty
    }
}


Time complexity:

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

Auxiliary Space: O(n)



Similar Reads

Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property states that it should be A Complete Binary Tree. For
4 min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Top 50 Problems on Heap Data Structure asked in SDE Interviews
A Heap is a special Tree-based Data Structure in which the tree is a complete binary tree. Generally, heaps are of two types: Max-Heap and Min-Heap. To know more about this Data Structure in-depth refer to the Tutorial on Heap Data-Structure. Given below are the most frequently asked interview questions on Heaps:  Easy Interview Questions on Heap D
2 min read
Stack Vs Heap Data Structure
What is Stack? A stack is a linear data structure where the last element entered exits first. The order of stack data structure might be LIFO, FILO: According to this technique, the piece that is in last will come out first. As an example, consider a stack of dishes stacked on top of each other. The plate we put last is on top, and because we take
3 min read
Applications of Heap Data Structure
Introduction:Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher priority are extracted first. This is useful in many applications such as scheduling tasks, handling interruptions, and processing events.Sorting Algorithms: Heapsort, a comparison-based sorting algorithm, is implemented using the Heap dat
11 min read
Leaf starting point in a Binary Heap data structure
Binary Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). In other words, we can say that it's an almost complete binary tree. A Binary heap is typically represented as array. If we take a closer look, we can noticed that in a Heap with number of nodes n, th
2 min read
Article Tags :
Practice Tags :