Skip to content

Commit 7ab36d3

Browse files
authored
Merge pull request #98 from jhanna60/main
Adding a heapsort algorithm
2 parents 2dbd83c + f995a04 commit 7ab36d3

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

HeapSort.java

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.util.Scanner;
2+
3+
public class HeapSort {
4+
public static void heapify(int a[],int i,int n)
5+
{
6+
7+
int l=2*i+1;
8+
int r=2*i+2;
9+
10+
11+
int temp,largest;
12+
13+
if(l<n && a[l]>a[i])
14+
largest=l;
15+
else
16+
largest=i;
17+
18+
if(r<n && a[r]>a[largest])
19+
largest=r;
20+
21+
if(largest !=i)
22+
{
23+
temp=a[largest];
24+
a[largest]=a[i];
25+
a[i]=temp;
26+
27+
heapify(a,largest,n);
28+
}
29+
30+
31+
}
32+
33+
public static void bheap(int a[])
34+
{
35+
36+
for(int i=(a.length/2)-1;i>=0;i--)
37+
{
38+
39+
heapify(a,i,a.length);
40+
41+
}
42+
43+
}
44+
45+
public static void Sort(int a[])
46+
{
47+
int temp,j,i;
48+
49+
bheap(a);
50+
51+
for( i=(a.length)-1; i>0;)
52+
{
53+
temp=a[0];
54+
a[0]=a[i];
55+
a[i]=temp;
56+
heapify(a,0,i--) ;
57+
58+
}
59+
60+
}
61+
62+
public static void printarray(int a[])
63+
{
64+
System.out.println();
65+
for (int j : a) {
66+
67+
System.out.print(j + " ");
68+
}
69+
70+
}
71+
public static void main(String[] args)
72+
{
73+
int n, res,i;
74+
Scanner s = new Scanner(System.in);
75+
System.out.print("Enter number of elements in the array:");
76+
n = s.nextInt();
77+
int[] a = new int[n];
78+
System.out.println("Enter "+n+" elements ");
79+
for( i=0; i < n; i++)
80+
{
81+
a[i] = s.nextInt();
82+
}
83+
84+
System.out.println( "elements in array ");
85+
printarray(a);
86+
Sort(a);
87+
System.out.println( "\nelements after sorting");
88+
printarray(a);
89+
90+
}
91+
}

0 commit comments

Comments
 (0)