I’m trying to create an algorithm visualiser for heap sort. In order to keep track of the swaps that happen during the heap sort execution, I created an animations array that will include the indexes of each swap. The heap sort animation works fine, but once I introduce the animations array into my code, I run into this error. TypeError: Cannot create property '375' on number '1'
Sort.js
heapSortVisualiser() {
const animations = heapSort(this.state.array);
console.log(animations);
}
HeapSort.js
// i is an index in arr, N is size of heap
function heapify(arr, N, i, animations) {
let largest = i; // initialise largest as root
let l = 2 * i + 1; // left = 2i + 1
let r = 2 * i + 2; // right = 2i + 2
// If left child is larger than root
if (l < N && arr[l] > arr[largest]) { largest = l; }
// If right child is larger than current largest
if (r < N && arr[r] > arr[largest]) { largest = r; }
// If largest is no longer the root
if (largest !== i) {
animations.push({
type: 'heapify',
index1: i,
index2: largest
})
[arr[i], arr[largest]] = [arr[largest], arr[i]]; // swap i and largest
// Recursively heapify the affected subtree
heapify(arr, N, largest);
}
}
export function heapSort(arr, animations = []) {
let N = arr.length;
// Build heap (rearrange array)
for (let i = Math.floor(N / 2) - 1; i >= 0; i--) { heapify(arr, N, i, animations) };
// Extract top element of heap one by one until heap is empty
for (let i = N - 1; i > 0; i--) {
animations.push({
type: 'sort',
index1: i,
index2: 0
})
[arr[i], arr[0]] = [arr[0], arr[i]] // move current root to end
// call max heapify on the reduced heap
heapify(arr, i, 0, animations);
}
return animations;
}
Initially I thought the problem was pushing a JavaScript object to the array was the issue, so I used JSON.stringify()
to convert the object to a string but the same error persists.
2
Answers
The error
TypeError: Cannot create property '375' on number '1'
suggests that somewhere in your code, you’re attempting to add a property to a number, which is not allowed in JavaScript.If you rewrite this function to TypeScript, it should be easier to spot a mistake.
But here’s my guess:
You call the
heapify(arr, N, largest);
function withoutanimations
once (an other times withanimations
).Trying to
.push
on an array which has not been passed might cause this error.You call the heapify(arr, N, largest); function without animations once (an other times with animations).
Trying to .push on an array which has not been passed might cause this error.