0% found this document useful (0 votes)
7 views7 pages

Day 21 Heap Sort

The document contains a Java implementation of the Heap Sort algorithm. It includes methods for sorting an array and heapifying elements to maintain the heap property. The main method reads an integer array from user input, sorts it using the Heap Sort algorithm, and prints 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 PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Day 21 Heap Sort

The document contains a Java implementation of the Heap Sort algorithm. It includes methods for sorting an array and heapifying elements to maintain the heap property. The main method reads an integer array from user input, sorts it using the Heap Sort algorithm, and prints 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 PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Heap Sort

1 import java.util.*;
2 public class Main {
3 public static void sort(int arr[]){
4 int N=arr.length;
5 for(int i=N/2-1; i>=0; i--)
6 heapify(arr,N,i);
7 for(int i=N-1; i>0; i--) {
8 int temp=arr[0];
9 arr[0]=arr[i];
10 arr[i]=temp;
11 heapify(arr,i,0);
12 }
13 }
14 static void heapify(int arr[], int N, int i){
15 int largest=i;
16 int l=2*i+1;
17 int r=2*i+2;
18 if(l<N && arr[l]>arr[largest])
19 largest=l;
20 if(r<N && arr[r]>arr[largest])
21 largest=r;
22
23 if(largest!=i) {
24 int swap=arr[i];
25 arr[i]=arr[largest];
26 arr[largest]=swap;
27 heapify(arr,N,largest);
28 }
29 }
30 public static void main(String args[]){
31 Scanner s=new Scanner(System.in);
32 int n=s.nextInt();
33 int arr[] = new int[n];
34 for(int i=0; i<n; i++)
35 arr[i]=s.nextInt();
36 sort(arr);
37 System.out.println("Sorted array is");
38 for(int i=0; i<n; i++)
39 System.out.print(arr[i] + " ");
40 System.out.println();
41 }
42 }
43
44
THANK YOU

You might also like