I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the recursive calls. Upon running the program, I keep getting errors stating 'cannot read property length of undefined'. I am feeling perplexed and struggling to pinpoint where exactly I am making a mistake.
In my initial function, I consistently divide the global array called visualArr, which is predetermined by the user and utilized for visualization purposes in my program. The subsequent function focuses on merging the divided arrays.
performMergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const middle = Math.floor(arr.length / 2);
let left = arr.slice(0, middle);
let right = arr.slice(middle, arr.length);
left = this.performMergeSort(left);
right = this.performMergeSort(right);
return this.performMerge(left, right);
}
The timer function within the second code snippet plays a significant role in providing real-time visuals during the sorting process. Nonetheless, I have a hunch that there might be a flaw either in my approach or in the TypeScript implementation. Any insights or feedback would be greatly valued.
performMerge(leftArr, rightArr) {
let lIdx = 0;
let rIdx = 0;
let i = 0;
timer(0, 100)
.pipe(takeWhile(() => leftArr.length > lIdx && rightArr.length > rIdx))
.subscribe(() => {
const lItem = leftArr[lIdx];
const rItem = rightArr[rIdx];
if (lItem > rItem) {
this.visualArr[i] = rItem;
rIdx++;
} else {
this.visualArr[i] = lItem;
lIdx++;
}
i++;
});
timer(0, 100)
.pipe(takeWhile(() => leftArr.length > lIdx ))
.subscribe(() => {
this.visualArr[lIdx] = leftArr[lIdx++];
});
timer(0, 100)
.pipe(takeWhile(() => rightArr.length > rIdx ))
.subscribe(() => {
this.visualArr[rIdx] = rightArr[rIdx++];
});
}