- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathheap_sort.java
More file actions
Latest commit
49 lines (44 loc) · 1.45 KB
/
Copy pathheap_sort.java
File metadata and controls
49 lines (44 loc) · 1.45 KB
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
importjava.util.*;
publicclassheap_sort {
publicvoidheapify(int[] ar, intn, inti) {
intmax = i, leftChild = 2 * i + 1, rightChild= 2 * i + 2;
// left child greater than root
if(leftChild < n && ar[leftChild] > ar[max]) max = leftChild;
// right child greater than root
if(rightChild < n && ar[rightChild] > ar[max]) max = rightChild;
// swap and heapify until max ele not found
if(max != i) {
intx = ar[i];
ar[i] = ar[max];
ar[max] = x;
heapify(ar, n, max);
}
}
publicvoidheapSort(int[] ar) {
intn = ar.length;
// max heap
for(inti = n / 2 - 1; i >= 0; i--) heapify(ar, n, i);
// heap sort
for(inti = n - 1; i > 0; i--) {
intx = ar[0];
ar[0] = ar[i];
ar[i] = x;
heapify(ar, i, 0);
}
}
publicstaticvoidmain(String[] args) {
// input code
Scanners = newScanner(System.in);
System.out.print("Enter Array Size : ");
intn = s.nextInt();
int[] ar = newint[n];
System.out.print("\nEnter Array Elements : ");
for(inti = 0; i < n; i++) ar[i] = s.nextInt();
// function call
HeapSorths = newHeapSort();
hs.heapSort(ar);
// display sorted array
System.out.print("\nSorted Array : ");
for(inti : ar) System.out.print(i + " ");
}
}