-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.java
More file actions
35 lines (29 loc) · 997 Bytes
/
MinHeap.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 MinHeap {
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[] minHeap = new int[n];
for (int i = 0; i < minHeap.length; i++) {
System.out.print("Enter the element: ");
minHeap[i] = scan.nextInt();
int child = i;
while (child > 0) {
int parent = (child - 1) / 2;
if (minHeap[child] < minHeap[parent]) {
int temp = minHeap[parent];
minHeap[parent] = minHeap[child];
minHeap[child] = temp;
child = parent;
} else {
break;
}
}
}
for (int i = 0; i < minHeap.length; i++) {
System.out.print(minHeap[i] + ", ");
}
scan.close();
}
}