Min Heap Sift Up Algorithm
What is printed to the console when the following code is executed?
public class HeapifyTest {
public static void main(String[] args) {
int[] heap = {5, 8, 12, 15, 3}; // 0-indexed min heap (except element 3 is out of place)
int child = 4; // value 3
while(child > 0) {
int parent = (child - 1) / 2;
if(heap[child] < heap[parent]) {
int temp = heap[child];
heap[child] = heap[parent];
heap[parent] = temp;
child = parent;
} else {
break;
}
}
for(int i = 0; i < heap.length; i++){
System.out.print(heap[i] + " ");
}
}
}
A
3 8 12 15 5
B
3 5 12 15 8
C
5 3 12 15 8
D
5 8 12 15 3
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | richa.tuli | 1 | 3 | 0m 16s | 64 |
| #2 | turan.musayev.28072020 | 0 | 1 | 0m 58s | -68 |
| #3 | lsj08030922 | 1 | 2 | 8h 47m | -31,569 |
Items per page:
10
1 – 3 of 3
APFIVE