Saturday, November 23, 2013

Write a program to find the first maximum and second maximum in an unsorted Array.

Easiest way to do this is to sort the array and then find the answer. In this case, time complexity will be equal to the sorting algorithm used i.e. minimum of O(nlogn), which is not the preferred way to do.
The better algorithm here is: take the first element of the array as the first maximum and second
element of the array as second maximum. Then loop through all elements:
  • If the number is larger than max then make it max, and make old max to second max.
  • Else if it is more than second max and not equal to first max then make it the second max.
  • In all other cases drop that number.
Code for your reference:

#include "stdio.h"

#define SIZE 10

void getFirstSecondMax(int *arr, int size)
{
    int i, max, sec_max;
    max  = arr[0];
    sec_max = arr[1];
    
    if (size < 2)
    {
        printf("Size of the Array is smaller than 2.\n");
        return;
    }
    for(i = 0; i < size; i++)
    {
        if(arr[i] > max) 
 {
            sec_max = max;
            max = arr[i];
        }
        else if((arr[i] > sec_max) && (arr[i] != max))
            sec_max = arr[i];
    }
    printf("First Maximum = %d, Second Maximum = %d\n", max, sec_max);
}

int main(void)
{
    int arr[SIZE] = {8, 4, 17, 1, 2, 1, 3, 18, 21, 4};    
    getFirstSecondMax(arr, SIZE);
}

No comments: