3 ways to find second largest number in array in JavaScript

preview_player
Показать описание
are you looking for answer of how to find the second largest number in any array in JavaScript?
In this video i have explained 3 ways you can find the second largest number in any array in JavaScript, and also given their time complexity.

The first method involves sorting whose time complexity is O(nlogn)
The second method involves two for loop whose time complexity is O(n)
The second method involves just one for loop whose time complexity is also O(n)
Рекомендации по теме
Комментарии
Автор

Third method is not working brother....

ayyappank
Автор

let arr2 = [2, 100, 22, 80, 5, 2]
let n = arr2.length;

let highest = -Infinity;
let secondHighest = -Infinity;

for (let i = 0; i < n; i++) {
if (arr2[i] > highest) {
secondHighest = highest;
highest = arr2[i];
}
}

console.log(highest, secondHighest);
answer is coming : 100, 2

ayyappank
Автор

Third method is wrong . kyuki usme jo highest element he uske pehele vali index ka element print ho raha he na ki second largest. Aapki arr list ma secondhighest 4 hi he or vi 6 ke pehele vali index pe he is liye aapko ho sahi lag raha hee aap ek bar arr change kar ke dekhiye

balram_patidar
Автор

This does not work for data set [12, 35, 1, 10, 34, 1]

abhishek