Related Articles

# Difference between Heaps and Sorted Array

• Last Updated : 25 Jun, 2021

1. Heap :
A heap is a tree based data structure in which tree should be almost complete. It is of two types i.e. max and min heap.

• Max heap In max heap if p is the parent and c is its child, then for every parent p the value of it is greater than or equal to the value of c
• Min heap In min heap if p is the parent and c is its child, then for every parent p value is less than or equal to the value of c.

Heap is also as priority queue. In which highest(in case of max heap) or lowest(in case of min heap) element is present at the root.
Heap is use in problems where we need to remove the highest or lowest priority element. A common implementation of heap is binary heap.

Implementation

• As heap can be implemented as tree but in these lots of storage wasted for storing pointers. Due to property of heap as it is almost complete binary tree it can be easily stored in array.
• Where root element is stored at first index and its child index can be calculated as
• Left child index = 2×r where r is index is root and array starting index is 0.
• Right child index = 2×r+1.
• And parent index can be calculated as floor(i/2) where i is the index of its left or right child.

Example : Example of Max heap

2. Sorted array :
A sorted array is a data structure in which elements are sorted in numerical, alphabetical, or by some other order and stored at contiguous memory locations. Sorted array example

• All data structures have their own pons and cons depending on the problems or algorithms they are used. For example heap is the best data structure in situations where we need optimality in finding(max or min), deleting(max or min) or inserting (max or min) element.
• And sorted array is used in situations in items need to stored in ascending or descending orders. For example in shortest-job-scheduling first algorithms where the processes(stored in array) need to be sorted according to burst time of the processes. So in case sorting array is required.

Difference between Heaps and Sorted Array :

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

My Personal Notes arrow_drop_up