Skip to content

Commit d87e3cf

Browse files
Heap Sort in Java
1 parent 54f503f commit d87e3cf

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

sorting/HeapSort.java

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*
2+
Copyright (C) Deepali Srivastava - All Rights Reserved
3+
This code is part of DSA course available on CourseGalaxy.com
4+
*/
5+
6+
import java.util.Scanner;
7+
8+
public class HeapSort
9+
{
10+
private HeapSort(){} //this class is not for instantiation
11+
12+
public static void sort(int[] a, int n)
13+
{
14+
buildHeap_BottomUp(a,n);
15+
16+
int maxValue;
17+
while(n>1)
18+
{
19+
maxValue=a[1];
20+
a[1]=a[n];
21+
a[n]=maxValue;
22+
n--;
23+
restoreDown(1,a,n);
24+
}
25+
}
26+
27+
public static void buildHeap_BottomUp(int[] arr, int n)
28+
{
29+
int i;
30+
for(i=n/2; i>=1; i--)
31+
restoreDown(i,arr,n);
32+
}
33+
34+
private static void restoreDown(int i, int[] a, int n)
35+
{
36+
int k=a[i];
37+
int lchild=2*i, rchild=lchild+1;
38+
39+
while(rchild<=n)
40+
{
41+
if( k>=a[lchild] && k>=a[rchild] )
42+
{
43+
a[i]=k;
44+
return;
45+
}
46+
else if(a[lchild] > a[rchild])
47+
{
48+
a[i]=a[lchild];
49+
i=lchild;
50+
}
51+
else
52+
{
53+
a[i]=a[rchild];
54+
i=rchild;
55+
}
56+
lchild=2*i;
57+
rchild=lchild+1;
58+
}
59+
60+
/*If number of nodes is even*/
61+
if(lchild==n && k<a[lchild])
62+
{
63+
a[i]=a[lchild];
64+
i=lchild;
65+
}
66+
a[i]=k;
67+
}
68+
69+
public static void main(String[] args)
70+
{
71+
int i,n;
72+
int[] a = new int[20];
73+
74+
Scanner scan = new Scanner(System.in);
75+
76+
System.out.print("Enter the number of elements : - ");
77+
n = scan.nextInt();
78+
79+
for(i=1; i<=n; i++)
80+
{
81+
System.out.print("Enter element " + i + " : ");
82+
a[i] = scan.nextInt();
83+
}
84+
85+
sort(a,n);
86+
87+
System.out.println("Sorted array is : ");
88+
for(i=1; i<=n; i++)
89+
System.out.print(a[i] + " ");
90+
System.out.println();
91+
}
92+
}
93+

0 commit comments

Comments
 (0)