From f995a04241410e1a5e72289700ec5aa6b2e4420a Mon Sep 17 00:00:00 2001 From: john hanna Date: Thu, 28 Oct 2021 19:07:34 +0100 Subject: [PATCH] Adding a heapsort algorithm --- HeapSort.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 HeapSort.java diff --git a/HeapSort.java b/HeapSort.java new file mode 100644 index 0000000..fa414de --- /dev/null +++ b/HeapSort.java @@ -0,0 +1,91 @@ +import java.util.Scanner; + +public class HeapSort { + public static void heapify(int a[],int i,int n) + { + + int l=2*i+1; + int r=2*i+2; + + + int temp,largest; + + if(la[i]) + largest=l; + else + largest=i; + + if(ra[largest]) + largest=r; + + if(largest !=i) + { + temp=a[largest]; + a[largest]=a[i]; + a[i]=temp; + + heapify(a,largest,n); + } + + + } + + public static void bheap(int a[]) + { + + for(int i=(a.length/2)-1;i>=0;i--) + { + + heapify(a,i,a.length); + + } + + } + + public static void Sort(int a[]) + { + int temp,j,i; + + bheap(a); + + for( i=(a.length)-1; i>0;) + { + temp=a[0]; + a[0]=a[i]; + a[i]=temp; + heapify(a,0,i--) ; + + } + + } + + public static void printarray(int a[]) + { + System.out.println(); + for (int j : a) { + + System.out.print(j + " "); + } + + } + public static void main(String[] args) + { + int n, res,i; + Scanner s = new Scanner(System.in); + System.out.print("Enter number of elements in the array:"); + n = s.nextInt(); + int[] a = new int[n]; + System.out.println("Enter "+n+" elements "); + for( i=0; i < n; i++) + { + a[i] = s.nextInt(); + } + + System.out.println( "elements in array "); + printarray(a); + Sort(a); + System.out.println( "\nelements after sorting"); + printarray(a); + + } +}