Heap Sort Lecture2 & 3
Heap Sort Lecture2 & 3
Algorithms
• Heap sort is a comparison-based sorting algorithm that works by first building a binary tree-like data
structure called a "heap", and then repeatedly extracting the maximum (or minimum) element from
the heap to build the sorted output.
• This efficient algorithm has wide applications in computer science, from priority queue
implementations to external sorting of large datasets.
Heaps
A heap is a special kind of binary tree that follows two main rules:
1.Shape property: The tree is "complete," which means that every level is fully filled except for possibly the last one,
where only the rightmost spots might be empty. The tree grows from top to bottom and left to right.
2.Heap property: In a max-heap, the value in each parent node is bigger than (or equal to) the values in its child
nodes. This rule ensures that the largest value is always at the top of the tree.
Heaps
In a min-heap, the value of each parent node is smaller than (or equal to) the values of its child
nodes. This means the smallest value is always at the top of the tree.
Maintaining the Heap property
property.
throughout.
Heapsort
Time Complexity
The time complexity of heap sort is O(n log n), where n is the size of Comparison to Other Sorting Algorithms
the input array. This is because the build max-heap step takes O(n) Compared to other popular sorting algorithms like quicksort and
time, and the extract maximum step takes O(log n) time for each of merge sort, heap sort has a slightly higher time complexity but a
the n elements. lower space complexity, making it a good choice for sorting large
Space Complexity
• The heap maximum operation returns the maximum element (the root) of the max-heap without removing it from the heap.
HEAP-EXTRACT-MAX
• The heap extract maximum operation removes the maximum element (the root) from the max-heap and then restructures
the heap to maintain the max-heap property.
Thank you