Find the largest and second largest element in an array using c language

find the largest and second largest number

We can find the largest and second largest number of an integers array using the c language. This question is also important and asks by the interviewer in an interview.

Let’s take an example, suppose here is an integer array iaData of 5 integers.

int iaData[5] = {3, 5, 123, 6, 1};

Here the largest number is 123 and the second largest number is 6.



A simple way to find the largest and second largest number is that sort the array in descending order and pick its first and second elements. Its first element will be the largest number and the second number will be the second largest number.The time complexity of this solution is O(n Log n).

OutPut:





Above method is not better because it scans the array twice. There is also another way to find the largest and second largest number in a single scan of the array. The time complexity of this solution is O(n).

Here is an algorithm to find two largest and second largest number in one traversal.

The algorithm to find largest and second largest number:

  • Create two variable iFirstLargest and iSecondLargest.
  • Initialize both variables as INT_MIN
    iFirstLargest = INT_MIN
    iSecondLargest = INT_MIN
  • Loop through all the elements and perform the below task
    1). If the current element is bigger than iFirstLargest, then update iFirstLargest and iSecondLargest.
    2). Else if the current element is bigger than iSecondLargest then update iSecondLargest.

OutPut:

 



Leave a Reply