Merge pull request #824 from Prashant-Bhapkar/second-largest-element

chore(C): add find second largest element in array
pull/833/head
Ashad 2022-09-01 20:49:29 +05:00 committed by GitHub
commit 170a706b1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 0 deletions

View File

@ -7,6 +7,7 @@
- [Reverse an array](arrays/reverse-array.c)
- [Maximum difference](arrays/maximum-difference.c)
- [Largest Element](arrays/largestElement.c)
- [Second Largest Element](arrays/secondLargestElement.c)
- [Sieve of Eratosthenes](arrays/sieve-of-eratosthenes.c)
## Bit Manipulation

View File

@ -0,0 +1,38 @@
//Second largest element in the array
#include<stdio.h>
#include<stdlib.h>
int second(int arr[],int size)
{
int max1=arr[0],max2;
for(int i=0;i<size;i++)
{
if(arr[i]>max1) //Find largest element in the array
{
max2=max1;
max1=arr[i];
}
else if (arr[i]>max2 && arr[i]<max1) // Find second largest element in the array
{
max2=arr[i];
}
}
printf("%d %d",max1,max2); // Print both first and second largest element in the array
}
int main()
{
int arr[]={2,5,1,12,18,88,23,45,4}; // Initialize array
int size=sizeof(arr)/sizeof(int); // Calculate array size
second(arr,size);
return 0;
}
/*
----------------Sample Output----------------
> 88 45
Time Compexity: O(n)
Space compexity: O(1)
*/