Three Largest elements in an array – C++ and Java Program

We have to find three largest elements in an array, condition is that time complexity should be O(n).

Below is the program in C++ to find three largest elements in an array

C++Java
#include <stdio.h>
#include <limits.h>
#include <iostream>
using namespace std;
  
void getThreeLargest(int array[], int size)
{
    int first, second, third;
  
    if (size < 3)
    {
        cout<<"Invalid Array!";
        return;
    }
  
    third = first = second = INT_MIN;
    
    for (int i = 0; i < size ; i ++) { if (array[i] > first)
        {
            third = second;
            second = first;
            first = array[i];
        }
  
        else if (array[i] > second)
        {
            third = second;
            second = array[i];
        }
  
        else if (array[i] > third)
            third = array[i];
    }
  
    cout<<"Three Largest elements: "<< first<<" "<< second<<" "<<third;
}
  
 
int main()
{
    int array[] = {9, 12, 16, 1, 5, 10};
    int size = sizeof(array)/sizeof(array[0]);
    getThreeLargest(array, size);
    return 0;
}
import java.util.*;

 public class Main{
       
    static void getThreeLargest(int array[]){
        int first, second, third;
        int size = array.length;
  
        if (size < 3){
            System.out.println("Invalid Array!");
            return;
        }
  
        third = first = second = Integer.MIN_VALUE;
    
        for (int i = 0; i < size ; i ++){ if (array[i] > first){
                third = second;
                second = first;
                first = array[i];
             }
  
             else if (array[i] > second){
                third = second;
                second = array[i];
            }
  
            else if (array[i] > third)
                third = array[i];
        }
  
        System.out.println("Three largest elements: "+first+" "+second+" "+third);
       
}
  
     
    public static void main(String args[]){
         
        int array[] = {9, 12, 16, 1, 5, 10};
        getThreeLargest(array);
     }
 }

Output

Three largest elements: 16 12 10

Leave a Reply

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