-
Notifications
You must be signed in to change notification settings - Fork 44
/
heap_sort.java
68 lines (61 loc) · 1.65 KB
/
heap_sort.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
import java.util.*;
public class heap_sort
{
void heapify(int ar[], int n, int i)
{
int largest = i; // Initialize
int l = 2*i; // left
int r = 2*i + 1; //right
if (l < n && ar[l] > ar[largest])
largest = l;
if (r < n && ar[r] > ar[largest])
largest = r;
if (largest != i)
{
int swap = ar[i];
ar[i] = ar[largest];
ar[largest] = swap;
heapify(ar, n, largest);
}
}
public void build_max_heap(int ar[])
{
int n = ar.length;
for (int i = n / 2 - 1; i >= 0; i--)
heapify(ar, n, i);
for (int i=n-1; i>=0; i--)
{
int temp = ar[0];
ar[0] = ar[i];
ar[i] = temp;
heapify(ar, i, 0);
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array : ");
int m = sc.nextInt();
int ar[] = new int[m];
System.out.println("Enter elements : ");
for(int i=0;i<m;i++)
{
ar[i]=sc.nextInt();
}
System.out.println("\nUnsorted Array: ");
int n = ar.length;
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+" ");
}
heap_sort ob = new heap_sort();
ob.build_max_heap(ar);
System.out.println("\n");
System.out.println("Sorted array: ");
n=ar.length;
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+" ");
}
}
}