diff --git a/Java/heapsort.java b/Java/heapsort.java new file mode 100644 index 0000000..af962c5 --- /dev/null +++ b/Java/heapsort.java @@ -0,0 +1,80 @@ +import java.util.*; +class Heap_Sort +{ + void printArray(int arr[],int n) + { + //int n = arr.length; + for (int i=0; i0) + { + int n = sc.nextInt(); + for(int i=0;i=0;i--) + heapify(arr,n,i); + } + + //Heapify function to maintain heap property. + void heapify(int arr[], int n, int i) + { + // Your code here + int l=2*i+1; + int r=2*i+2; + int largest=i; + + if(larr[largest]) largest=l; + if(rarr[largest]) largest=r; + + if(i!=largest){ + int temp=arr[i]; + arr[i]=arr[largest]; + arr[largest]=temp; + heapify(arr,n,largest); + } + } + + //Function to sort an array using Heap Sort. + public void heapSort(int arr[], int n) + { + //code here + buildHeap(arr,n); + for(int i=n-1;i>=0;i--){ + //swap first last + int temp=arr[i]; + arr[i]=arr[0]; + arr[0]=temp; + heapify(arr,i,0); + } + } + } + \ No newline at end of file