From c38636145daafac6007b18ef87a97d931f79f4d4 Mon Sep 17 00:00:00 2001 From: THEAYUSHIMISHRA <146479275+THEAYUSHIMISHRA@users.noreply.github.com> Date: Sun, 22 Oct 2023 08:34:04 +0530 Subject: [PATCH] Create HeapSort HeapSort on Binary Search Tree --- HeapSort | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 HeapSort diff --git a/HeapSort b/HeapSort new file mode 100644 index 0000000..2ecc07f --- /dev/null +++ b/HeapSort @@ -0,0 +1,52 @@ +#include +#include +void swap(int *x,int *y) +{ + int temp; + temp=*x; + *x=*y; + *y=temp; +} +void heapify(int arr[],int n,int i) +{ //initial largest as root + int largest=i; + int l=(2*i)+1;//left + int r=(2*i)+2;//right + //left child is greater han right child + if(larr[largest]) + largest=l; + //right child is greater han left child + if(rarr[largest]) + largest=r; + if(largest!=i) //if largest is not root + { + swap(& arr[i],& arr[largest]); + //recursively heapify the affected subtree + heapify(arr,n,largest); + } +} +void heapsort(int arr[],int n) +{ + int i; + //build heap(rearrange array) + for(i=(n/2)-1;i>=0;i--) + heapify(arr,n,i); + for(i=n-1;i>0;i--) //one by one extract element from heap + { + swap(&arr[0],&arr[i]); //move curr to end + heapify(arr,i,0); //calling max heapify on reduced heapify + } +} +int main() +{ + int arr[10],i,n; + printf("Enter number of elements to be sorted:\t"); + scanf("%d",&n); + printf("Enter the element\n"); + for(i=0;i