-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHeapsort.java
69 lines (51 loc) · 1.28 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
import java.util.*;
class Heapsort{
//public static void swap(int a,int b){ int temp = a;a = b;b = temp;}
public static void max_heapify(int arr[],int i,int n){
int l = i*2+1;
int r = l + 1;
int largest=i;
if(l<=n && arr[l]>arr[i])
{
largest = l;System.out.println("left child big for index "+i+": "+arr[largest]);
}
if(r<=n && arr[r]>arr[largest])
{
largest = r;System.out.println("right child big for index "+i+": "+arr[largest]);
}
if(largest!=i)
{
int temp = arr[i];arr[i] = arr[largest];arr[largest] = temp;// SWAPPING VALUES OF A[LARGEST] AND A[I]
//NOW THE SMALLER VALUE GOES AT A[LARGEST] INDEX
max_heapify(arr,largest,n);
}
}
public static void build_max_heap(int arr[],int n)
{
for(int i=n/2;i>=0;i--)
{
max_heapify(arr,i,n);
for(int j=0;j<n;j++)
{
System.out.print(arr[j]+ " ");
}
System.out.println();
}
}
public static void heapsort(int arr[],int n){
build_max_heap(arr,n);
for (int i=n;i>=1;i-- ) {
int temp = arr[i];arr[i] = arr[0];arr[0] = temp;
max_heapify(arr,0,i-1);
}
}
public static void main(String[] args) {
int arr[] = {4,1,3,2,16,9,10,14,8,7};
int n = arr.length;
heapsort(arr,n-1);
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+ " ");
}
}
}