0

Min Heap Data Structure

Here is my code for Min binary heap, Correct me if i am wrong. public class BinaryHeap { int a[] = new int[11]; int size = 11; int last = 0; public BinaryHeap() { for (int i = 0; i < 11; i++) a[i] = Integer.MIN_VALUE; } public void insert(int element) { if (last < size) { a[last + 1] = element; last++; if (last != 1) heapifybottomtotop(last); } } public void heapifybottomtotop(int last) { int root; root = last / 2; if (a[last] < a[root]) { int temp = a[last]; a[last] = a[root]; a[root] = temp; } else { return; } heapifybottomtotop(root); } public void peek() { if (last == 0) { System.out.println("No elements"); return; } else { System.out.println("The top element is " + a[1]); return; } } public void size() { System.out.println("The size is " + last); } public void traversal() { System.out.println("The elements are "); for (int i = 1; i <= last; i++) { System.out.print(" " + a[i]); } } public void extractMin() { if(last>=1){ System.out.println("The min elemnt before extracting is " + a[1]); a[1] = a[last]; last--; heapifytoptobottom(1); System.out.println("The min elemnt after extracting is " + a[1]); } } private void heapifytoptobottom(int root) { int left, right; left = root * 2; right = (root * 2) + 1; if (left <= last && a[left] < a[root]) { int temp = a[left]; a[left] = a[root]; a[root] = temp; root = left; heapifytoptobottom(root); } else if (right <= last && a[right] < a[root]) { int temp = a[right]; a[right] = a[root]; a[root] = temp; root = right; heapifytoptobottom(root); } else { return; } } }

30th Jul 2019, 8:13 PM
Divya Dharshini
Divya Dharshini - avatar
2 odpowiedzi
0
missing end of code here
31st Jul 2019, 2:38 AM
zemiak
0
@Zemiah Sorry didnt notice, now added porperly,. Sorry for wrong indentation because of character constraint.
31st Jul 2019, 10:46 AM
Divya Dharshini
Divya Dharshini - avatar