×

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array.

C/C++ Program to Find the Largest Three Different Elements in an Array. Expected time complexity is O (n), but additional space is O (1).

Examples:

Input: array [] = {20, 18, 6, 10, 46, 75}
Output: 75, 46, 20

1st Approach:

Algorithm

  • We will create three elements called maximum1, maximum2, and maximum3 that hold the values of the three largest elements and assign their values to array [0].
  • Then, for each element, we shall loop from i -> 1 to n - 1.
  • if ( array [i] > maximum1 ) -> maximum 3 = maximum 2, maximum 2 = maximum1 , maximum1 = array [i].
  • else if ( array [i] > maximum2 ) -> maximum3 = maximum2, maximum2 = array [i].
  • else if ( array [i] > max3 ) -> maximum3 = array [i].
  • We will print all max three values at the completion of the loop.

The above algorithm is implemented as follows-

C Program:

#include <stdio.h>


void locatethethreelargestelements ( int array [], int array_size )
{
   int maximum1, maximum2, maximum3;
   maximum3 = maximum1 = maximum2 = array [0];
   for ( int i = 0; i < array_size; i++ )
   {
      if ( array[i] > maximum1 )
	  {
         maximum3 = maximum2;
         maximum2 = maximum1;
         maximum1 = array[i];
      }
      else if ( array [i] > maximum2 ) 
	  {
         maximum3 = maximum2;
         maximum2 = array [i];
      }
      else if ( array [i] > maximum3 )
         maximum3 = array [i];
   }
   printf ("\nLargest Three Different Elements in an Array are %d %d %d", maximum1 , maximum2 , maximum3 ) ;
}
int main ()
{
   int array [] = { 20, 18, 6, 10, 46, 75 };
   int n = sizeof ( array ) / sizeof ( array [0] ); 
   printf ("The array elements are : \n" );
   for (int i = 0; i < n; i++)  
      printf ("%d \t", array[i]); 
     locatethethreelargestelements (array, n);
   return 0;
} 

C++ Program:

#include <iostream>
using namespace std;


void locatethethreelargestelements ( int array [], int array_size )
{
   int maximum1, maximum2, maximum3;
   maximum3 = maximum1 = maximum2 = array [0];
   for ( int i = 0; i < array_size; i++ )
   {
      if ( array [i] > maximum1 )
	  {
         maximum3 = maximum2;
         maximum2 = maximum1;
         maximum1 = array[i];
      }
      else if ( array [i] > maximum2 ) 
	  {
         maximum3 = maximum2;
         maximum2 = array [i];
      }
      else if ( array [i] > maximum3 )
         maximum3 = array [i];
   }
   cout << endl << "\nLargest Three Different Elements in an Array are "<< maximum1 
   														 <<", "
														 << maximum2 
														 <<", "
														 << maximum3;
}
int main ()
{
   int array [] = { 20, 18, 6, 10, 46, 75 };
   int n = sizeof ( array ) / sizeof ( array [0] ); 
   cout << "The array elements are : " <<endl;
   for (int i = 0; i < n; i++)  
      cout << array[i] <<"\t"; 
     locatethethreelargestelements (array, n);
   return 0;
}

Output:

The array elements are :
20      18      6       10      46      75
Largest Three Different Elements in an Array are 75 46 20

Time Complexity: O (n)

Space Complexity: O (1)

2nd Approach:

Algorithm:

  • The array will be sorted using a sorting method.
  • Print the largest three digits.

C Program:

#include <stdio.h>
#include <stdlib.h>
 
int comparefunc ( const void* x, const void* y )
{
    return (*(int*)x - *(int*)y);
}


void findthreelargest( int array [], int no )
{
    qsort ( array, no, sizeof(int),
          comparefunc ) ;
  
printf ("Largest Three Different Elements in an Array are :");
    int checkpt = 0, cnt = 1;
    for ( int i = 1; i <= no; i++ ) 
	{
        if (cnt < 4)
		 {
            if ( checkpt != array [no - i] ) 
			{
                printf ("%d ", array [no - i]);
                checkpt = array [no - i];
                cnt++;
            }
        }
        else
            break;
    }
}
 
int main()
{
    int array[] = { 56, 78, 93, 21, 60, 100 };
    
    int no = sizeof ( array ) / sizeof ( array [0] );
    findthreelargest ( array, no );
}

C++ Program:

#include <bits/stdc++.h>
using namespace std;


void findthreelargest ( int array[], int no )
{
	cout <<"Largest Three Different Elements in an Array are: ";
	sort( array, array + no );
	int checkpt = 0, cnt = 1;
	for ( int i = 1; i <= no; i++ ) 
	{
		if ( cnt < 4 ) 
		{
			if ( checkpt != array [ no - i ] ) 
			{
				cout << array [ no - i ] << " ";
				checkpt = array [ no - i] ;
				cnt ++;
			}
		}
		else
			break;
	}
}
int main()
{
	int array[] = { 56, 78, 93, 21, 60, 100 };
	int n = sizeof ( array ) / sizeof (array [0] );
	findthreelargest ( array, n );
}

Output:

Largest Three Different Elements in an Array are: 100 93 78

Time Complexity: O (n log n)

Space Complexity: O (1)


Related Topics

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.

For Loop in C

The Syntax of For Loop for (initialization statement; test expression; update statement) {     /* main body of the FOR loop */ } How does For loop work? In for loop, the initialization command is...

3 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

Floor() Function in C

Floor() function is a built-in function in C which is defined in the math.h header file. This function is used to return the nearest integer value which is less than...

4 minutes read.

fflush in C

In this article, we will understand what is fflush(), the need for fflush and fflush(stdin), and fflush(stdout). The fflush() function is used to clear the output buffer and move the buffered...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Functions in C

What is function? Functions are defined as the set of announcements which take inputs, perform operations and provide results. The operation of a function only performs when the function gets called....

4 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.