Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. /**
  2. * MinHeap.java
  3. * A generic MinHeap implementation. Is probably trash.
  4. * @author Mr. Kramer
  5. */
  6. import java.util.ArrayList;
  7. public class MinHeap <T extends Comparable>
  8. {
  9. ArrayList <T> arr = new ArrayList<T>();
  10.  
  11. /**
  12. * insert an object into the heap
  13. * @param object to insert
  14. */
  15. void insert(T value) {
  16. // add value to end
  17. arr.add(value);
  18. int curr = arr.size() - 1;
  19. // sift the value up
  20. int parent = ( curr - 1 ) / 2;
  21. while (parent >= 0 && arr.get(curr).compareTo(arr.get(parent)) < 0){
  22. T temp = arr.get(curr);
  23. arr.set(curr, arr.get(parent));
  24. arr.set(parent, temp);
  25. curr = parent;
  26. parent = ( curr - 1 ) / 2;
  27. }
  28. }
  29.  
  30. /**
  31. * delete the top of the heap and return it
  32. * @return object at the top of the heap or null if heap is empty
  33. */
  34. T delete() {
  35. if (arr.size() == 0) return null;
  36.  
  37. T returnMe = arr.get(0);
  38.  
  39. // replace root with last element
  40. arr.set(0, arr.get(arr.size() - 1));
  41. //remove the last element
  42. arr.remove(arr.size() - 1);
  43.  
  44. int curr = 0;
  45.  
  46. // sift down
  47. boolean done = false;
  48. while (!done) {
  49. int leftChild = curr * 2 + 1;
  50. int rightChild = curr * 2 + 2;
  51. int swapChild = arr.size() - 1 ;
  52. if (leftChild >= arr.size()) {
  53. done = true;
  54. } else if (rightChild >= arr.size() ||
  55. arr.get(leftChild).compareTo(arr.get(rightChild)) < 0) {
  56. // left child is smaller
  57. swapChild = leftChild;
  58. } else {
  59. // right child is smaller
  60. swapChild = rightChild;
  61. }
  62.  
  63. if (!done && arr.get(swapChild).compareTo(arr.get(curr)) < 0) {
  64. T temp = arr.get(curr);
  65. arr.set(curr,arr.get(swapChild));
  66. arr.set(swapChild, temp);
  67. curr = swapChild;
  68. } else {
  69. done = true;
  70. }
  71. }
  72.  
  73. return returnMe;
  74. }
  75.  
  76. /**
  77. * return the object at the top of the heap without deleting
  78. * @return object at top of heap or null if heap is empty
  79. */
  80. T peek() {
  81. if (arr.size() == 0) return null;
  82. return arr.get(0);
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement