Basic Sorting and Searching Algorithms for Arrays, at a glance
Heap SortHeapsort uses the property of Heaps to sort an array. The Heap data structure is an array object that can be viewed as a complete and balanced binary tree. Min (Max)-Heap has a property that for every node other than the root, the value of the node is at least (at most) the value of its parent. Thus, the smallest (largest) element in a heap is stored at the root, and the subtrees rooted at a node contain larger (smaller) values than does the node itself. Algorithm:It starts with building a heap by inserting the elements entered by the user, in its place. 1. Increase the size of the heap as a value is inserted. 2. Insert the entered value in the last place. 3. Compare the inserted value with its parent, until it satisfies the heap property and then place it at its right position. Now once the heap is built remove the elements from top to bottom, while maintaining the heap property to obtain the sorted list of entered values. 1. heap[1] is the minimum element. So we remove heap[1]. Size of the heap is decreased. 2. Now heap[1] has to be filled. We put the last element in its place and see if it fits. If it does not fit, take minimum element among both its children and replaces parent with it. 3. Again see if the last element fits in that place. Property:Best case performance – when the input array is already sorted O(nlogn). Worst case performance – when the input array is in reverse order O(nlogn). Average case performance – O(nlogn) It does not require any extra space for sorting, hence O(1) extra space. It is not stable. Complete Tutorial document with example:Heap Sort - C Program Source Code#include<stdio.h>
Related Tutorials :
Testing Zone For Programmers-Try out our online Multiple-Choice-Question tests in Programming and Computer Science! |
Computer Science >