-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.java
54 lines (52 loc) · 1.55 KB
/
heap.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
import java.util.*;
class Main {
static void heapify(int arr[], int n, int ind) {
int largest = ind;
int n1 = 2 * ind + 1;
int n2 = 2 * ind + 2;
if (n1 < n && arr[largest] < arr[n1]) {
largest = n1;
}
if (n2 < n && arr[largest] < arr[n2]) {
largest = n2;
}
if (ind != largest) {
int temp = arr[ind];
arr[ind] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of the array:- ");
int n = sc.nextInt();
System.out.println("");
int[] arr = new int[n];
System.out.println("Enter Elements of array:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
sc.close();
for (int i = (n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
int ct = 1;
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
System.out.print("Pass" + ct++ + " -");
for (int j = 0; j < n; j++) {
System.out.print(arr[j] + "");
}
System.out.println(" ");
}
System.out.println("Final Sorted Array is :-");
for (int j = 0; j < n; j++) {
System.out.print(arr[j] + "");
}
System.out.println("");
}
}