Data Structures: Insert an Element into a Max Heap
This commit is contained in:
		
							parent
							
								
									1395b95b9c
								
							
						
					
					
						commit
						0812d4b56a
					
				
							
								
								
									
										28
									
								
								Data Structures/heapInsert.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								Data Structures/heapInsert.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,28 @@
 | 
			
		||||
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/insert-an-element-into-a-max-heap
 | 
			
		||||
 | 
			
		||||
var MaxHeap = function () {
 | 
			
		||||
  // Only change code below this line
 | 
			
		||||
  this.heap = [];
 | 
			
		||||
 | 
			
		||||
  this.insert = (item) => {
 | 
			
		||||
    this.heap.push(item);
 | 
			
		||||
    let me = this.heap.length - 1;
 | 
			
		||||
    let parent = Math.trunc((me - 1) / 2);
 | 
			
		||||
    while (parent != me && this.heap[parent] < this.heap[me]) {
 | 
			
		||||
      const tmp = this.heap[parent];
 | 
			
		||||
      this.heap[parent] = this.heap[me];
 | 
			
		||||
      this.heap[me] = tmp;
 | 
			
		||||
      me = parent;
 | 
			
		||||
      parent = Math.trunc((me - 1) / 2);
 | 
			
		||||
    }
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  this.print = () => this.heap;
 | 
			
		||||
  // Only change code above this line
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
const h = new MaxHeap();
 | 
			
		||||
for (let i = 0; i < 10; i++) {
 | 
			
		||||
  h.insert(Math.trunc(Math.random() * 100));
 | 
			
		||||
}
 | 
			
		||||
console.log(h.print());
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user