-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminHeap.java
More file actions
39 lines (31 loc) · 903 Bytes
/
minHeap.java
File metadata and controls
39 lines (31 loc) · 903 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
36
37
38
import java.util.* ;
import java.io.*;
public class Solution
{
public static void heapify(int arr[], int n, int i){
int smallest_node = i;
int left_node = 2*i + 1;
int right_node = 2*i + 2;
if(left_node < n && arr[smallest_node] > arr[left_node]){
smallest_node = left_node;
}
if(right_node < n && arr[smallest_node] > arr[right_node]){
smallest_node = right_node;
}
if(smallest_node != i){
int temp = arr[smallest_node];
arr[smallest_node] = arr[i];
arr[i] = temp;
heapify(arr, n, smallest_node);
}
}
public static int[] buildMinHeap(int[] arr)
{
// Write your code here
int n = arr.length;
for(int i = (n/2)-1; i >= 0; i--){
heapify(arr, n, i);
}
return arr;
}
}