Searching Second Largest Element

QUESTION

Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.

“TESTCASE_1”: “6\n12 35 1 10 34 1\n###—###SEPERATOR—###—\nThe second largest element is 34”, “TESTCASE_2”: “5\n10 5 10 34 30\n###—###SEPERATOR—###—\nThe second largest element is 30”, “TESTCASE_3”: “4\n14 67 39 12\n###—###SEPERATOR—###—\nThe second largest element is 39”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <stdio.h>
int main()
{
int n;
  scanf("%d",&n);
  int arr[n];
  int i,j;
  for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
  for(i=0;i<n;i++)
  {
    for(j=i+1;j<n;j++)
    {
    if(arr[i]>arr[j])
       {
         int temp=arr[i];
      arr[i]=arr[j];
      arr[j]=temp;
    }
    }
  }
  //float sum=arr[n-1]+arr[n-2];
  printf("The second largest element is %d",arr[n-2]);
	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro