Find First and Second Biggest In An Array, Without Sorting It: C


We assume that a[0] has first biggest and a[1] has the second biggest value.

Now check if this assumption is correct, if not, swap the values.

 
 if( sbig > fbig )
 {
    temp = sbig;
    sbig = fbig;
    fbig = temp;
 }

Now since we have already checked with a[0] and a[1], we start the comparison from a[2], till N.

for(i=2; i < n ; i++)
 if(a[i] > fbig)
 {
sbig = fbig;
fbig = a[i];
 }
 else if(a[i] > sbig)
sbig = a[i];

Now, if a[i] contains a number which is bigger than fbig, we transfer the value of a[i] to fbig and the value present in fbig to sbig;
If the value of a[i] is not bigger than fbig, then we check it with sbig. If a[i] is bigger than sbig, then we assign the value of a[i] to sbig.

This way, at the end of the loop fbig will have the first biggest and sbig will have the second biggest element/number in the array.

Video Tutorial: Find First and Second Biggest In An Array, Without Sorting It: C



YouTube Link: https://www.youtube.com/watch?v=DzZvT87WuGQ [Watch the Video In Full Screen.]



Full source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include < stdio.h >
#include < conio.h >
 
void main()
{
int a[20], N, i, fbig, sbig, temp;
clrscr();
 
printf("Enter array limit\n");
scanf("%d", &N);
 
printf("Enter %d array elements\n", N);
for(i=0; i < n ; i++)
 scanf("%d", &a[i]);
 
fbig = a[0];
sbig = a[1];
 
if( sbig > fbig )
{
   temp = sbig;
   sbig = fbig;
   fbig = temp;
}
 
for(i=2; i < n ; i++)
 if(a[i] > fbig)
 {
sbig = fbig;
fbig = a[i];
 }
 else if(a[i] > sbig)
sbig = a[i];
 
 printf("First Big is %d and Second big is %d", fbig, sbig);
 
 getch();
 
}

Output:
Enter array limit
6
Enter 6 array elements
99
108
777
723
786
999
First Big is 999 and Second big is 786

Leave a Reply

Your email address will not be published. Required fields are marked *