NOTE: This is just for studying and bettering myself. I know of the available sort method for arrays. I'm just trying to get the basics of TCO down.
Currently trying to work on a sort algorithm using recursion. However when I try to process large datasets (+4000 objects), I am still getting a stack overflow error. I'm trying to implement TCO. I'm fairly new to the concept but I think I have the gist of it. However, I'm still receiving a stack overflow error.
const sort = (arr, counter) => {
if (!counter) {
counter = arr.length - 1;
}
for (let n = 1; n <= counter; n++) {
if(arr[n - 1] < arr[n]) {
let placeHolder = arr[n];
arr[n] = arr[n - 1];
arr[n - 1] = placeHolder;
}
}
counter -= 1;
return counter === 0 ? arr : sort(arr, counter);
};
function sortRecursive(arr) {
return sort(arr);
}
UPDATE:
I managed to get it working, but I don't quite understand why. I managed to handle 100,000 recursions with no problems. I had to move the boolean that checks if counter is defined. However, I do not quite understand why that made it work.
const sort = (arr, counter) => {
if (!counter) {
counter = arr.length - 1;
}
for (let n = 1; n <= counter; n++) {
if(arr[n - 1] < arr[n]) {
let placeHolder = arr[n];
arr[n] = arr[n - 1];
arr[n - 1] = placeHolder;
}
}
counter -= 1;
if (counter === 0) {
return arr;
} else {
return sort(arr, counter);
}
};
function sortRecursive(arr) {
return sort(arr, arr.length - 1);
}
OUTPUT:
let firstArr = [];
let secondArr = [];
for (let x = 0; x < 100000; x++) {
firstArr.push(Math.ceil(Math.random() * 100000));
secondArr.push(Math.ceil(Math.random() * 100000));
}
sortRecursive(firstArr);
//Array[100000]