now since we have equipped ourselves with the knowledge of heaps,we can use it for some practical purposes.
The most important use of heaps is to sort an array.
how we will do that?
lets look step wise step
suppose you have an array (starting with index 1) like this
A[]={,5,13,2,25,7,17,20,8,4};
lets make a simple complete binary tree with the above array
you will get this structure
c code to implement heap sort
[cpp]
void heap_sort(int A[]){
build_max_heap(A);
for(i=size;i=>2;--i){
swap(A[1],A[i]);
max_heapify(A,i-1,1);
}
time complexity
best case =O(n) {example 5 1 2 3 4}
worst case =O(nlogn)
}
[/cpp]
0 comments: