Second Largest Number in Array Javascript Algorithm | Problem 1

preview_player
Показать описание
We are going to write a Javascript program to find out:
The Second Largest Number/Element in an unsorted Array.
Рекомендации по теме
Комментарии
Автор

The code will break if the 0th element from the array is the largest. Both the if and else if will not satisfy the condition.
Instead initialize largest and secondLargest variables to 0

rohansonawane
Автор

What extension you are using to autocomplete for
for loop at line 6?

arunaagt
Автор

else if (arr [ i ] > secondLargestNumber) {
secondLargestNumber = arr [ i ]
}

Why is this necessary?

vakhtangelisabedashvili
Автор

Make video find largest number without array

Vishal-ilmz
Автор

If the array is [25, 20, 15, 10]. Then you can't find second largest number

oxwuizl
Автор

This won’t work for arrays having duplicate items. You’ll have to add one more ‘else if’ between your ‘if’ and ‘else if’:

else if (nums[i] == LargestNumber) {
continue;
}

ht
Автор

Please provide a video to find second largest and second smallest number at a time

VinnuKanna
Автор

Nice explanation but if array contains larger duplicate value eg.[1, 3, 5, 2, 80, 44, 60, 90, 100, 100] then code will break.

rohitthakre
Автор

if duplicates are present in the array....
const arr = [1, 4, 2, 7, 4, 7]

const getSecLarNum = (arr=[1, 4, 2, 7, 4, 7])=>{
let largestNum = arr[0];
let secLargNum = arr[0];

for(i=0; i < arr.length ; i++){
if(arr[i] > largestNum){
secLargNum = largestNum;
largestNum = arr[i];
}else if(arr[i] == largestNum){
continue;
}else if(arr[i] > secLargNum){
secLargNum = arr[i]
}
}

return secLargNum;
}

console.log(getSecLarNum())

harshads
Автор

Thank you

minor fix
/* second largest number */

const secondLargestNumber = (arr) => {
let largestNumber = -Infinity

let secondLargest = -Infinity

for ( var i = 0; i < arr.length; i++ ) {
if (arr[i] > largestNumber) {
/* before updating laregest lets save it to secondLargest */
secondLargest = largestNumber

largestNumber = arr[i]

} else if( arr[i] > secondLargest && arr[i] != largestNumber) {
secondLargest = arr[i]
}
}

return secondLargest
}


console.log(secondLargestNumber([1, 3, 5, 2, 80, 44, 60, 90, 100, 100]))

at
Автор

// Your code is too long.
const input=[1, 2, -2, 11, 7, 22, 25, 1];
const input1=[1, 4, 7, 2, 4, 8, 10, 7];

function smax(input){
let arr=input.sort((a, b)=>a-b);
return arr[arr.length-2];}
console.log(smax(input));
console.log(smax(input1));

//Output:22
8

mominuber
Автор

Use Number.NEGATIVE_INFINITY to correct issues in this code.

KushEzio