   # Find the second largest element in an integer array,without using sorting techniques and complexity must not exceed O(n)

185 views
Find the second largest element in an integer array,without using sorting techniques and complexity must not exceed O(n) posted Mar 20, 2016

Input - 13, 2, 41, 5 , 46, 7
first_big = 12 // first big
second_big = 2 // second big

for (i = 2; i < size - 1; i++)
{
if (arr[i] > first_big)
{
second_big = first_big;
first_big = arr[i];
}
}

second_big = 12
first_big = 41

No change

### Third iteration:

second_big = 41
first_big = 46

This is final result.
If someone has better logic to solve this problem then please share. answer Mar 20, 2016 by
your logic can't be applied on any input i guess. output in:41 46 12 3 17 1 is first_big=41 and second_big=46  and output in 41 46 12 3 98 1 is first big=98,second big=41.in both cases output is wrong.please let me know if i understood your logic wrong, i guess u have taken the first and second integer of the array as first_big and second_big.
however slightly modified version works fine.
int main()
{
int arr[]={41,12,18,46,1};
int second_big;
int first_big=arr>arr?arr:arr;
if(first_big==arr)
second_big=arr;
else
second_big=arr;
for (i = 2; i < size ; i++)
{
if (arr[i] > first_big)
{
second_big = first_big;
first_big = arr[i];
}
printf("%d",second_big);
}
return 0;
}

### Find the 2nd highest element:

``````int findSecondHighest(int *arr,int len){

int max=0,second_highest,i;
for(i=0;i<len;i++){
if(max<arr[i]){
max=arr[i];
second_highest=max;
}
}
return second_highest;
}
``````

Time Complexity=O(n) answer Apr 4, 2016
Similar Questions