Advertisement
gelita

MaxHeap Class

Feb 28th, 2020
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Complete the 'heapsort' function below.
  3.  *
  4.  * The function is expected to return an INTEGER_ARRAY.
  5.  * The function accepts INTEGER_ARRAY arr as parameter.
  6.  */
  7.  
  8. function heapsort(arr) {
  9.    
  10.     //initialize the heap length to the size of the array
  11.     let heapSize = arr.length;
  12.    
  13.     //create a max heap from the array (heapify)
  14.     //for every element starting from the right side of the array
  15.     for(let i = Math.floor((arr.length- 2)/2); i >=0; i--) {
  16.         //bubble down that element
  17.         bubbleDown(i);
  18.     }
  19.    
  20.     //create bubble down function to help heapify and maintain heap
  21.     function bubbleDown(parent) {
  22.         //use get child function to get the larger child
  23.         let child = getChild(parent);
  24.         //while child is in heap and larger than the parent
  25.         while(child <= heapSize - 1 && arr[child] > arr[parent]) {
  26.             //swap
  27.             [arr[child], arr[parent]] = [arr[parent], arr[child]]
  28.             //get new child from new position and update parent position
  29.             parent = child;
  30.             child = getChild(child);
  31.         }
  32.     }
  33.    
  34.     //create a remove function to remove an element from the heap
  35.     function removeFromHeap() {
  36.         //swap the element at position 0 with the elemnt at the end of the heap
  37.         [arr[0], arr[heapSize - 1]] = [arr[heapSize -1], arr[0]];
  38.         //reduce heap size by 1
  39.         heapSize--;
  40.         //bubble down the new root (index 0)
  41.         bubbleDown(0);
  42.     }
  43.    
  44.     //create a helper to get the child for swapping with bubble down
  45.     function getChild(parent) {
  46.         //let left child = parent value * 2 + 1
  47.         let leftChild = parent*2 + 1;
  48.         //if left child the last element of the heap or is greater than the element one greater than it
  49.         if(leftChild >= heapSize - 1 || arr[leftChild] >= arr[leftChild + 1]) {
  50.             //return left
  51.             return leftChild;
  52.         } else {
  53.         //else
  54.             //return left + 1
  55.             return leftChild + 1;
  56.         }
  57.     }
  58.    
  59.     //remove elements from the heap to sort
  60.     //while heap size is > 1
  61.     while(heapSize > 1) {
  62.         //remove from heap
  63.         removeFromHeap();
  64.     }
  65.    
  66.     //return the array
  67.     return arr;  
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement