×

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

Ceil function in C

Introduction In the C Programming Language, the ceil function is a library function which is used to obtain the ceil value, i.e., it returns the smallest integer that is greater than...

4 minutes read.

C program that does not Suspend when Ctrl+Z is Pressed

In Programming when a program breakdown and runs surprisingly in the terminal compiler the developer has the ability to prevent the program from running unequivocally. For expressly halting the program,...

3 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 minutes read.

How to include graphics.h in C?

How to include graphics.h in code blocks? Graphics .h is a header that allows drawing lines, rectangles, ovals, arcs, polygons, pictures, and strings on a graphical window by giving access to...

6 minutes read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Structure in C

Why Structure came into the picture? In the actual world, we deal with entities that are collections of objects rather than tiny bits of data like integers, characters, floats, etc. So,...

4 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

How to move a text in C

A text can be moved to the desired location in the output based on the coordinates provided in the gotoxy() function. What is gotoxy() function? In C language, gotoxy() is a pre-defined...

3 minutes read.

Character Class Tests in C

Introduction The <ctype.h> is a header file in C which is used to declare functions for testing characters. This header file of the C standard library is used to declare multiple...

4 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.

While Loop Syntax in C

What is Loop? The statements in the sequence are repeatedly executed via looping statements in C until the condition is met. The body of a loop and a control statement make...

4 minutes read.

C Token

C Token and Keyword The C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in the C program is...

2 minutes read.

Find out Power without using POW function in C

Introduction: In this discussion, we will discuss how we find out power without using the POW function in C. In this article, you'll understand how to compute integer powers in...

3 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 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.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.