0% found this document useful (0 votes)
15 views2 pages

Dsa 9

The document defines a heapify method that recursively sorts an array into a max heap by comparing elements at each index to their children and swapping if any children have a greater value. It then uses the heapify method to sort an input array into a max heap, repeatedly swapping the first and last elements and calling heapify to maintain the heap property, outputting the sorted array.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

Dsa 9

The document defines a heapify method that recursively sorts an array into a max heap by comparing elements at each index to their children and swapping if any children have a greater value. It then uses the heapify method to sort an input array into a max heap, repeatedly swapping the first and last elements and calling heapify to maintain the heap property, outputting the sorted array.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;
class main{
static void heapify(int arr[],int n,int ind){
int largest=ind;
int n1=2*ind+1;
int n2=2*ind+2;
if(n1<n && arr[largest]<arr[n1]){
largest=n1;
}
if(n2<n && arr[largest]<arr[n2]){
largest=n2;
}
if(ind!=largest){
int temp=arr[ind];
arr[ind]=arr[largest];
arr[largest]=temp;
heapify(arr,n,largest);
}
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array:");
int n=sc.nextInt();
System.out.println("");
int[] arr=new int[n];
System.out.println("Enter Elements of Array:");
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
sc.close();
for(int i=(n/2)-1;i>=0;i--){
heapify(arr,n,i);
}
int ct=1;
for(int i=n-1;i>0;i--){
int temp=arr[0];
arr[0]=arr[i];
arr[i]=temp;
heapify(arr,i,0);
System.out.println("Pass"+ct++ +":");
for(int j=0;j<n;j++){
System.out.print(arr[j]+" ");
}
System.out.println("");
}
System.out.println("FInal Sorted Array is:");
for(int j=0;j<n;j++){
System.out.print(arr[j]+"");
}
System.out.println("");
}
}
OUTPUT:
Enter Size of Array:
5

Enter Elements of Array:


4
7
2
3
1
Pass1:
43217
Pass2:
31247
Pass3:
21347
Pass4:
12347
FInal Sorted Array is:
12347

You might also like