The problem lies in the logic you are using. You can not build the largest only based on the two elements you analyze, as those that have been analyzed backwards will be disregarded.
I put your code with some console.log
through the medium in order to see the comparisons and assignments he makes:
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));
Note that for the array:
[10,3,1,6,7,2]
- Compares the
10
with 3
to discover that the greatest is the 10
- But then immediately compares the
3
with the 1
and says the greatest is 3
.
This is because in your code only the two current numbers matter, which means that only the last comparison will prevail. Yet when you’re in the last element of doing:
b = array[i+1];
i+1
will already be out of the valid positions and b
will stay with undefined
. As with the if
next:
if (!b) {
b = 0;
}
Like b
has undefined
gets into the if
and gets 0
causing the a
is larger (unless negative). You can see this in the last comparison shown in snippet previous, the "A comparar 2 com 0"
. In conclusion, your role encontraMaior
always returns the last element, which may coincidentally be the largest.
There is no way to fix without even changing the logic. Since you want to implement by hand do the normal which 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 re-invent the wheel and use the functions that already exist for this purpose, in this case the Math.max
who 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 to the function max
.
Do the table test in your role and you will understand what is wrong.
– Woss
to begin, this code will give error in the last item of the array:
b = array[i+1]
. You are trying to read the next element, this will give error, you just need to look at the current element (indexi
)– Ricardo Pontual
@Ricardopunctual Will not give error in the last element but return
undefined
in relation tob = array[i+1]
which will be caught byif (!b) {
. The problem really lies in the logic itself.– Isac
@Isac when he said error was not in the sense of Exception, but will generate a comparison error that can invalidate if the penultimate number is the largest, because for example any number, 10. Compare
10 < undefined
or10 > undefined
or10 === undefined
all returnfalse
invalidating the logic– Ricardo Pontual
I understand your question, but if you give a Sort array in your array before starting the comparisons, I think it will be more right.
– Lucas Ferreira