Finding second largest element in an array code example
Example 1: find second largest number in array javascript
var secondMax = function (){
var arr = [20, 120, 111, 215, 54, 78];
var max = Math.max.apply(null, arr);
arr.splice(arr.indexOf(max), 1);
return Math.max.apply(null, arr);
};
Example 2: find second largest number in array javascript
var secondMax = function (arr){
var max = Math.max.apply(null, arr),
maxi = arr.indexOf(max);
arr[maxi] = -Infinity;
var secondMax = Math.max.apply(null, arr);
arr[maxi] = max;
return secondMax;
};
Example 3: find second max element in array in 1 iteration
#include <stdio.h>
#include <limits.h>
#define MAX_SIZE 1000
int main()
{
int arr[MAX_SIZE], size, i;
int max1, max2;
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max1 = max2 = INT_MIN;
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d", max2);
return 0;
}