I am attempting to write a solution to a pretty common alg. Input is a non sorted array and the output should be an array of the three highest valuest sorted.
My approach is to default set the first three items of the array to be the three largest. Loop through every element in the array starting from idx 3 and run each value through a series of functions that compares that value to each of the present 3 highest.
MY CODE
function findThreeLargestNumbers(array) {
let currentHighest = array[0];
let secondHighest = array[1];
let thirdHighest = array[2]
for(i = 3; i < array.length; i++){
compareFirst(array[i], currentHighest, secondHighest, thirdHighest);
}
console.log(currentHighest, secondHighest, thirdHighest)
}
function compareFirst(value, currentHighest, secondHighest, thirdHighest){
if(value >= currentHighest){
let pastFirst = currentHighest;
currentHighest = value;
compareSecond(pastFirst, secondHighest, thirdHighest)
}else{
compareSecond(value, secondHighest, thirdHighest)
}
}
function compareSecond(value, secondHighest, thirdHighest){
if(value >= secondHighest){
let pastSecond = secondHighest;
secondHighest = value;
compareThird(pastSecond, thirdHighest);
}else{
compareThird(value, thirdHighest)
}
}
function compareThird(value, thirdHighest){
if(value >= thirdHighest){
thirdHighest = value;
}
}
after this is all finished in the console.log I see nothing has changed from the variables I have set above. Meaning the functions are not updating the values set in the parent function.
My approach might be way off but I'm confused as to why the values wont update globally.
currentHighest(the parameter), not the globalcurrentHighest(the argument).