The problem is with the logic itself that you are using. You can not build the largest just based on the two elements you analyze, because those that have been parsed back will be disregarded.
I put your code with console.log
through the middle to see the comparisons and assignments it does:
function encontraMaior(array) {
var maior;
if(array.length < 1) {
throw new Error('Empty array');
}
for (let i = 0; i < array.length; i++) {
let a, b;
a = array[i];
b = array[i+1];
if (!b) {
b = 0;
}
console.log('A comparar ${a} com ${b}');
if (a > b) {
maior = a;
}
else if (b > a) {
maior = b;
}
else if(a === b) {
maior = a;
}
console.log('O maior é agora ${maior}');
}
return maior;
}
let arr = [10,3,1,6,7,2];
console.log(encontraMaior(arr));
Notice that for the array:
[10,3,1,6,7,2]
- Compare
10
with 3
to find that the largest is 10
- But then it compares
3
to 1
and says that the largest is 3
.
This is because in your code only the two current numbers are of interest, which means that only the last comparison will prevail. However when you are in the last element when doing:
b = array[i+1];
i+1
will already be out of valid positions and b
will have undefined
. So with if
that follows:
if (!b) {
b = 0;
}
As b
has undefined
enters if
and gets 0
causing a
to be greater (unless it is negative). You can see this in the last comparison that is shown in the snippet , the "A comparar 2 com 0"
. In conclusion, its function encontraMaior
always returns the last element, which may coincidentally be the largest.
There is no way to correct without even changing logic. Since you want to implement by hand make it normal that it is much simpler:
function encontraMaior(array) {
if(array.length < 1) {
throw new Error('Empty array');
}
var maior = array[0]; //mais alto iniciado como o primeiro elemento
for (let i = 1; i < array.length; ++i){
// ^--- Começa no segundo pois o primeiro já foi considerado
//se o valor que tem no momento é maior que o mais alto
if (array[i] > maior){
maior = array[i]; //atualiza o mais alto
}
}
return maior;
}
let arr = [10,3,1,6,7,2];
console.log(encontraMaior(arr));
In real situations do not reinvent the wheel and use the functions that already exist for this, in this case the Math.max
you mentioned:
function encontraMaior(array){
return Math.max(...array);
}
let arr = [10,3,1,6,7,2];
console.log(encontraMaior(arr));
In this last example I used the spread operator
to expand the elements for the max
function.