Heap Sort
Heap sort is a one type of sorting algorithm.Worst-case performance : O(n log n)
Best-case performance : Ώ(n), O(n log n)
Average-case performance : O(n log n)
For more information click here
Code
/*****Heap sort*****/ #include<stdio.h> //Function declaration void manage(int *, int); void heapsort(int *, int, int); //Main function start int main(){ int arr[20]; int i,j,size,tmp,k; //Taking the number of element printf("Enter the number of elements to sort : "); scanf("%d",&size); //Taking the elements from user 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++) { //Swap tmp=arr[1]; arr[1]=arr[size]; arr[size]=tmp; size--; //Function call for heap sort heapsort(arr,1,size); } printf("\nAfter sorting the elements are: "); size=j; for(i=1; i<=size; i++) printf(" %d ",arr[i]); return 0; } //Function definition 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; } //Function definition 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
Enter the number of elements to sort : 7 Enter 1 element : 8 Enter 2 element : 4 Enter 3 element : 6 Enter 4 element : 9 Enter 5 element : 11 Enter 6 element : 2 Enter 7 element : 5 After sorting the elements are: 2 4 5 8 6 9 11