Sie sind auf Seite 1von 5

Program 4

AIM:-WAP to implement of Heap Sort Theory:Heapsort is a comparison based sorting algorithm to create a sorted array (or list), and is part of the selection sort family. Heap sort is actually a two step algorithm. 1.The first step is to build a heap out of the data. 2.The second step begins with removing the largest element from the heap. We insert the removed element into the sorted array. For the first element, this would be position zero of the array. Next we reconstruct the heap and remove the next largest item, and insert it into the array. After we have removed all the objects from the heap, we have a sorted array. We can vary the direction of the sorted elements by choosing a min-heap or maxheap in step one.

ALGORITHM:manage( int a[ ], int n ) for k = (n-1)/2 to 0 heapsort(k, a, n) for k = n-1 to 1 v = a[0] largest value on heap a[0] = a[k] a[k] = v a[k] is no longer in heap Heap from a[0] to a[N-1], size N heapsort(int k, int a[ ], int N) v = a[k] j = 2k + 1 left child of k since heap begins in a[0] while( j N-1 ) // while left child is within heap if( j < N-1 && a[j] < a[j+1]) ++j if( v && a[j] ) break a[k] = a[j] k=j j =2k+1 a[k] = v

COMPLEXITY: BuildHeap takes O(n) time. Heapify takes O(log n) time. Heapsort makes one call to BuildHeap and n1 calls to Heapify. Thus, the complexity of Heapsort is O(n + (n 1) log n) = O(n log n).

APPLICATIONS:One of the biggest application of heap sort is constructing a priority queue basic idea is that, we want to know the tasks that carry the highest priority, given a large number of things to do. and this is exactly how heap sort works. Another application is interval scheduling. we may have a list of tasks with certain start and finish times and we want to do as many of these tasks as possible in a given period of time. in order to sort the finish time efficient algorithm to use is heap sort .

PROGRAM:
#include<stdio.h> #include<conio.h> void manage(int *, int); void heapsort(int *, int, int); int main() { clrscr(); int arr[20]; int i,j,size,tmp,k; printf("Enter the number of elements to sort : "); scanf("%d",&size);

for(i=1; i<=size; i++) { printf("Enter %d element : ",i); scanf("%d",&arr[i]); manage(arr,i); } j=size; for(i=1; i<=j; i++) { tmp=arr[1]; arr[1]=arr[size]; arr[size]=tmp; size--; heapsort(arr,1,size); } printf("\n\t Heap sorted elements\n\n"); size=j; for(i=1; i<=size; i++) printf("%d ",arr[i]); getch(); return 0; } void manage(int *arr, int i) { int tmp; tmp=arr[i];

while((i>1)&&(arr[i/2]<tmp)) { arr[i]=arr[i/2]; i=i/2; } arr[i]=tmp; } void heapsort(int *arr, int i, int size) { int tmp,j; tmp=arr[i]; j=i*2; while(j<=size) { if((j<size)&&(arr[j]<arr[j+1])) j++; if(arr[j]<arr[j/2]) break; arr[j/2]=arr[j]; j=j*2; } arr[j/2]=tmp; }

OUTPUT: