Last test case is showing that this code maybe is not right. Please correct my code.
Last test case: The sort method should return an array containing all items added to the min heap in sorted order.
**Your code so far**
function isSorted(a){
for(let i = 0; i < a.length - 1; i++)
if(a[i] > a[i + 1])
return false;
return true;
}
// Generate a randomly filled array
function createRandomArray(size = 5){
let a = new Array(size);
for(let i = 0; i < size; i++)
a[i] = Math.floor(Math.random() * 100);
return a;
}
const array = createRandomArray(25);
var MinHeap = function() {
// Only change code below this line
this.heap=[null];
this.insert=ele=>{
this.heap.push(ele);
let heap=this.heap;
(function minHeap(index){
if(data<heap[Math.floor(index/2)]&&index>1){
[heap[index],heap[Math.floor(index/2)]]=[heap[Math.floor(index/2)],data];
minHeap(Math.floor(index/2));
}
})(this.heap.length-1);
};
this.remove=()=>{
let arr=[...this.heap];
let min=arr.splice(1,1);
this.heap=[null];
for(let i=0;i<arr.length;i++)
this.insert(arr[i]);
return min[0];
};
this.sort=()=>{
let result=[];
while(heap.length>1)
result.push(this.remove());
return result;
};
// Only change code above this line
};
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
.
Challenge: Implement Heap Sort with a Min Heap
Link to the challenge: