Heap Sort with a Min Heap

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:

let heap = [null];
	
	this.insert = function(num) {
		heap.push(num);
		if (heap.length > 2) {
			let idx = heap.length - 1;
			while (heap[idx] < heap[Math.floor(idx/2)]) {
				if (idx >= 1) {
					[heap[Math.floor(idx/2)], heap[idx]] = [heap[idx], heap[Math.floor(idx/2)]];
					if (Math.floor(idx/2) > 1) {
						idx = Math.floor(idx/2);
					} else {
						break;
					};
				};
			};
		};
	};
	
	this.remove = function() {
		let smallest = heap[1];
		if (heap.length > 2) {
			heap[1] = heap[heap.length - 1];
			heap.splice(heap.length - 1);
			if (heap.length == 3) {
				if (heap[1] > heap[2]) {
					[heap[1], heap[2]] = [heap[2], heap[1]];
				};
				return smallest;
			};
			let i = 1;
			let left = 2 * i;
			let right = 2 * i + 1;
			while (heap[i] >= heap[left] || heap[i] >= heap[right]) {
				if (heap[left] < heap[right]) {
					[heap[i], heap[left]] = [heap[left], heap[i]];
					i = 2 * i
				} else {
					[heap[i], heap[right]] = [heap[right], heap[i]];
					i = 2 * i + 1;
				};
				left = 2 * i;
				right = 2 * i + 1;
				if (heap[left] == undefined || heap[right] == undefined) {
					break;
				};
			};
		} else if (heap.length == 2) {
			heap.splice(1, 1);
		} else {
			return null;
		};
		return smallest;
	};
  
	this.sort = function() {
		let result = new Array();
		while (heap.length > 1) {
			result.push(this.remove());
		};
		return result;
	};

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.