Sample:
myArray = [1, 2, 4, 10, 20,100]
How to find second largest value without sorting the array or latering its contents?
function secondLargest(arr) {
var max1st = arr[0];
var max2nd = 0;
for(var i=0; i<arr.length; i++) {
if(arr[i] > max1st) {
max2nd = max1st;
max1st = arr[i];
}
else if(arr[i] > max2nd && arr[i] != max1st) {
max2nd = arr[i];
}
}
return max2nd;
}
console.log(secondLargest([100,2,4,54,27,98,99]));
console.log(secondLargest([10,22,48,54,27,8]));
console.log(secondLargest([2,4,54,27,98,99]));
console.log(secondLargest([21,42,87,27,8,99]));
console.log(secondLargest([10,10,10,5,6,7,8]));
99 48 98 87 8
This can be done in one pass in a for loop.
var biggest = myArray[0];
var nextbiggest = myArray[0];
for(var i=0;i<myArray.length;i++){
if(myArray[i]>biggest){
nextbiggest = biggest;
biggest = myArray[i];
}
else if(myArray[i]>nextbiggest && myArray[i]!=biggest)
nextbiggest = myArray[i];
}
console.log(nextbiggest);
If you pass the var myArray = [10,10,10,5,6,7,8]; then the second highest to be 8 not 10.Getting wrong output in given array.
let secondMax = (input) =>{
let max = Math.max.apply(null,input)
input.splice(input.indexOf(max),1)
max=Math.max.apply(null,input);
return max;
}
console.log(secondMax([10,20,30,40,50]));
var biggest = myArray[0];
var nextbiggest = myArray[0];
for(var i=0;i<myArray.length;i++){
if(myArray[i]>biggest){
nextbiggest = biggest;
biggest = myArray[i];
}
else if(myArray[i]>nextbiggest && myArray[i]!=biggest)
nextbiggest = myArray[i];
}
console.log(nextbiggest);
Find the third largest number in an array given an array of numbers with at least a size `3` without sorting. in Javascript
-
If I put the largest number first then I can't find the right answer.
3 years ago