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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more