forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.java
74 lines (56 loc) · 1.14 KB
/
HeapSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package Sorting;
public class heapify {
public void sort(int a[])
{
int n=a.length;
for(int i=(n/2)-1;i>=0;i--)
{
hepify(a,n,i);
}
for(int i=n-1;i>=0;i--) {
int temp=a[0];
a[0]=a[i];
a[i]=temp;
hepify(a,i,0);
}
}
static void hepify(int a[],int n,int i)
{
int larest;
int left=(2*i)+1;
int right=(2*i)+2;
if(left<n && a[left]>a[i])
{
larest=left;
}
else{
larest=i;
}
if(right<n && a[right]>a[larest])
{
larest=right;
}
if(larest!=i)
{
int temp;
temp=a[i];
a[i]=a[larest];
a[larest]=temp;
hepify(a,n,larest);
}
}
static void display(int a[])
{
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
public static void main(String args[])
{
int a[]={10,12,5,8,6,4,3,89};
heapify data=new heapify();
data.sort(a);
display(a);
}
}