-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.java
More file actions
35 lines (29 loc) · 997 Bytes
/
MaxHeap.java
File metadata and controls
35 lines (29 loc) · 997 Bytes
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
import java.util.Scanner;
public class MaxHeap {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the numbers of elements: ");
int n = scan.nextInt();
int[] MaxHeap = new int[n];
for (int i = 0; i < MaxHeap.length; i++) {
System.out.print("Enter the element: ");
MaxHeap[i] = scan.nextInt();
int child = i;
while (child > 0) {
int parent = (child - 1) / 2;
if (MaxHeap[child] > MaxHeap[parent]) {
int temp = MaxHeap[parent];
MaxHeap[parent] = MaxHeap[child];
MaxHeap[child] = temp;
child = parent;
} else {
break;
}
}
}
for (int i = 0; i < MaxHeap.length; i++) {
System.out.print(MaxHeap[i] + ", ");
}
scan.close();
}
}