DEV Community

Ganesh K S
Ganesh K S

Posted on

Second Largest Element in an array

This is the given array

let arr=[1,2,4,7,7,5]
Enter fullscreen mode Exit fullscreen mode

Declare the two variables

let firstMax;
let secondMax;
Enter fullscreen mode Exit fullscreen mode

Then find out the which is greater in the first 2 index values

if(arr[0] > arr[1]){
  firstMax = arr[0]
}else{
  secondMax=arr[1]
}

if(arr[1] > arr[0]){
  firstMax = arr[1]
}else{
  secondMax=arr[0]
}
Enter fullscreen mode Exit fullscreen mode

Then begin the loop from 2 to last index of the array

In the first loop

Image description

In the second loop

Image description

In the third loop

Image description

In the fourth loop

Image description

Complete solution to find the second largest in the array

let arr=[1,2,4,7,7,5]

let firstMax;
let secondMax;

if(arr[0] > arr[1]){
  firstMax = arr[0]
}else{
  secondMax=arr[1]
}

if(arr[1] > arr[0]){
  firstMax = arr[1]
}else{
  secondMax=arr[0]
}

for(let i=2;i<arr.length;i++){
  if(arr[i] > firstMax){
    secondMax=firstMax;
    firstMax=arr[i];
  }

  if(arr[i] > secondMax && arr[i] < firstMax){
    secondMax = arr[i]
  }

}

console.log("firstMax",firstMax)
console.log("secondMax",secondMax)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)