This is my first project in Javascript and I am trying to create a sorting visualizer. I specifically stuck on the merge sort algorithm. The algorithm seems to work when I output it to console but the DOM element are not updating when they are being changed.
So for example when the programs run nodes[k] = leftArr[i]; or nodes[k] = rightArr[j]; the nodes are being updated in the program itself but its not updating in the DOM and I can't figure out why?
I've tried replaceWith() and replaceChild() but that just seems to delete elements and breaks the whole program.
Merge Sort Algorithm
export function mergeSort(nodes) {
if (nodes.length < 2) {
return;
}
// console.log(nodes);
const middleIdx = Math.floor(nodes.length / 2);
let leftArr = Array.from(nodes).slice(0, middleIdx);
let rightArr = Array.from(nodes).slice(middleIdx, nodes.length);
mergeSort(leftArr);
mergeSort(rightArr);
merge(nodes, leftArr, rightArr);
}
function merge(nodes, leftArr, rightArr) {
let i = 0;
let j = 0;
let k = 0;
while (i < leftArr.length && j < rightArr.length) {
if (leftArr[i].offsetHeight <= rightArr[j].offsetHeight) {
nodes[k] = leftArr[i];
i++;
} else {
nodes[k] = rightArr[j];
j++;
}
k++;
}
while (i < leftArr.length) {
nodes[k] = leftArr[i];
i++;
k++;
}
while (j < rightArr.length) {
nodes[k] = rightArr[j];
j++;
k++;
}
}