fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class MaxHeap
  9. {
  10. int capacity;
  11. int size;
  12. int arr[];
  13. MaxHeap(int capacity){
  14. this.capacity = capacity;
  15. size = 0;
  16. this.arr = new int[capacity];
  17. }
  18. int parent(int i) {
  19. return (i - 1) / 2;
  20. }
  21. /*returns the left child of ith Node*/
  22. int left(int i) {
  23. return 2 * i + 1;
  24. }
  25. /*Returns the right child of the ith Node*/
  26. int right(int i) {
  27. return 2 * i + 2;
  28. }
  29. void insert(int ele){
  30. if(size == capacity){
  31. System.out.println("Heap overflow");
  32. return;
  33. }
  34. arr[size] = ele;
  35. int k = size;
  36. size++;
  37. while(k!=0&&arr[k]>arr[parent(k)]){
  38. //swap
  39. int temp = arr[parent(k)];
  40. arr[parent(k)] = arr[k];
  41. arr[k] = temp;
  42. k = parent(k);
  43. }
  44. }
  45. int getMax() {
  46. return arr[0];
  47. }
  48. public static void main (String[] args) throws java.lang.Exception
  49. {
  50. // your code goes here
  51. MaxHeap h = new MaxHeap(20);
  52. h.insert(4);
  53. h.insert(1);
  54. h.insert(2);
  55. h.insert(6);
  56. h.insert(7);
  57. h.insert(3);
  58. h.insert(8);
  59. h.insert(5);
  60. System.out.println("Max value is " + h.getMax());
  61. h.insert(99);
  62. System.out.println("Max value is " + h.getMax());
  63. }
  64. }
Success #stdin #stdout 0.12s 55752KB
stdin
Standard input is empty
stdout
Max value is 8
Max value is 99