Posted on by Kalkicode
Code Array

Find three largest element in array

In various programming scenarios, there's often a need to find the largest elements in an array. This program focuses on identifying the three largest elements within an array of integers. The task is to efficiently analyze the array and extract the three most significant values from it.

Problem Statement and Description

Consider an array of integers. The goal is to write a program that identifies and outputs the three largest elements present in the array. These largest elements should be arranged in descending order. If the array contains less than three elements, the program should gracefully handle this situation and not produce any output.

Example

Let's take two instances to demonstrate the program's functionality.

  1. Input
    Array: [8, 2, 0, 6, -2, 6, -1, 9, 4, 3]
    Output
    Largest Elements: 9, 8, 6
  2. Input
    Array: [9, 2, -7, 4, 1, 3, 7, 22, 8, -4]
    Output
    Largest Elements: 22, 9, 8

Idea to Solve the Problem

To find the three largest elements in the array, a commonly employed strategy is to keep track of the largest, second-largest, and third-largest values encountered so far. By iterating through the array once, it's possible to update these values and arrive at the desired result.

Pseudocode

function findThreeLargest(arr):
    if size of arr < 3:
        return
    first = INT_MIN
    second = INT_MIN
    third = INT_MIN
    for element in arr:
        if element > first:
            third = second
            second = first
            first = element
        else if element > second:
            third = second
            second = element
        else if element > third:
            third = element
    output "Largest Elements:", first, second, third

Algorithm Explanation

  1. Begin by checking whether the array size is less than 3. If so, exit the function, as finding three largest elements is not feasible.
  2. Initialize three variables, first, second, and third, with the minimum possible integer value (INT_MIN).
  3. Iterate through each element in the array.
    • Compare the current element with first. If it's larger, update first, second, and third accordingly.
    • If the current element is not larger than first but larger than second, update second and third.
    • If the current element is not larger than first or second but larger than third, update third.
  4. After iterating through the array, print the three largest elements: first, second, and third.

Code Solution

// C Program
// Find three largest element in array
#include <stdio.h>

#include <limits.h>
 //Function which is display array elements
void display(int arr[], int size)
{
	for (int i = 0; i < size; ++i)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
}
//Method which is finding the third largest element in given array
void three_largest(int arr[], int size)
{
	if (size < 3)
	{
		return;
	}
	//initial set the minimum value of variables
	int first = INT_MIN;
	int second = INT_MIN;
	int third = INT_MIN;
	for (int i = 0; i < size; ++i)
	{
		//Check if whether array element i value is largest than of variable first 
		if (arr[i] > first)
		{
			//modify the value of all three variables
			//like a swap operation of two variable
			third = second;
			second = first;
			//Assign a new big value
			first = arr[i];
		}
		else if (arr[i] > second)
		{
			//When get second largest element
			third = second;
			//Assign a new big value
			second = arr[i];
		}
		else if (arr[i] > third)
		{
			//When get third largest element
			third = arr[i];
		}
	}
	display(arr, size);
	printf("Resultant largest\n");
	printf("first : %d second : %d  third : %d\n\n", first, second, third);
}
int main()
{
	//Define array elements
	int arr1[] = {
		8,
		2,
		0,
		6,
		-2,
		6,
		-1,
		9,
		4,
		3
	};
	int size = sizeof(arr1) / sizeof(arr1[0]);
	three_largest(arr1, size);
	//Define array elements
	int arr2[] = {
		9,
		2,
		-7,
		4,
		1,
		3,
		7,
		22,
		8,
		-4
	};
	size = sizeof(arr2) / sizeof(arr2[0]);
	three_largest(arr2, size);
	return 0;
}

Output

8 2 0 6 -2 6 -1 9 4 3
Resultant largest
first : 9 second : 8  third : 6

9 2 -7 4 1 3 7 22 8 -4
Resultant largest
first : 22 second : 9  third : 8
/*
  Java Program
  Find three largest element in array
*/
class MyArray
{
	//Function which is display array elements
	public void display(int[] arr, int size)
	{
		for (int i = 0; i < size; ++i)
		{
			System.out.print(" " + arr[i] + " ");
		}
		System.out.print("\n");
	}
	//Method which is finding the third largest element in given array
	public void three_largest(int[] arr, int size)
	{
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		int first = Integer.MIN_VALUE;
		int second = Integer.MIN_VALUE;
		int third = Integer.MIN_VALUE;
		for (int i = 0; i < size; ++i)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			{
				//modify the value of all three variables
				//like a swap operation of two variable
				third = second;
				second = first;
				//Assign a new big value
				first = arr[i];
			}
			else if (arr[i] > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr[i];
			}
			else if (arr[i] > third)
			{
				//When get third largest element
				third = arr[i];
			}
		}
		display(arr, size);
		System.out.print("Resultant largest\n");
		System.out.print("first : " + first + " second : " + second + " third : " + third + "\n\n");
	}
	public static void main(String[] args)
	{
		MyArray obj = new MyArray();
		//Define array elements
		int[] arr1 = {
			8,
			2,
			0,
			6,
			-2,
			6,
			-1,
			9,
			4,
			3
		};
		int size = arr1.length;
		obj.three_largest(arr1, size);
		//Define array elements
		int[] arr2 = {
			9,
			2,
			-7,
			4,
			1,
			3,
			7,
			22,
			8,
			-4
		};
		size = arr2.length;
		obj.three_largest(arr2, size);
	}
}

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
/*
  C++ Program
  Find three largest element in array
*/
#include<iostream>
#include<limits.h>
using namespace std;
class MyArray
{
	public:
		//Function which is display array elements
		void display(int arr[], int size)
		{
			int i = 0;
			while (i < size)
			{
				cout << " " << arr[i] << " ";
				++i;
			}
			cout << "\n";
		}
	//Method which is finding the third largest element in given array
	void three_largest(int arr[], int size)
	{
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		int first = INT_MIN;
		int second = INT_MIN;
		int third = INT_MIN;
		int i = 0;
		while (i < size)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			{
				//like a swap operation of two variable
				//modify the value of all three variables
				third = second;
				second = first;
				//Assign a new big value
				first = arr[i];
			}
			else if (arr[i] > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr[i];
			}
			else if (arr[i] > third)
			{
				//When get third largest element
				third = arr[i];
			}++i;
		}
		this->display(arr, size);
		cout << "Resultant largest\n";
		cout << "first : " << first << " second : " << second << " third : " << third << "\n\n";
	}
};
int main()
{
	MyArray obj ;
	int arr1[] = {
		8,
		2,
		0,
		6,
		-2,
		6,
		-1,
		9,
		4,
		3
	};
	int size = sizeof(arr1) / sizeof(arr1[0]);
	obj.three_largest(arr1, size);
	int arr2[] = {
		9,
		2,
		-7,
		4,
		1,
		3,
		7,
		22,
		8,
		-4
	};
	size = sizeof(arr2) / sizeof(arr2[0]);
	obj.three_largest(arr2, size);
	return 0;
}

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
/*
  C# Program
  Find three largest element in array
*/
using System;
class MyArray
{
	//Function which is display array elements
	public void display(int[] arr, int size)
	{
		int i = 0;
		while (i < size)
		{
			Console.Write(" " + arr[i] + " ");
			i++;
		}
		Console.Write("\n");
	}
	//Method which is finding the third largest element in given array
	public void three_largest(int[] arr, int size)
	{
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		int first = int.MinValue;
		int second = int.MinValue;
		int third = int.MinValue;
		int i = 0;
		while (i < size)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			{
				//like a swap operation of two variable
				//modify the value of all three variables
				third = second;
				second = first;
				//Assign a new big value
				first = arr[i];
			}
			else if (arr[i] > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr[i];
			}
			else if (arr[i] > third)
			{
				//When get third largest element
				third = arr[i];
			}
			i++;
		}
		display(arr, size);
		Console.Write("Resultant largest\n");
		Console.Write("first : " + first + " second : " + second + " third : " + third + "\n\n");
	}
	public static void Main(String[] args)
	{
		MyArray obj = new MyArray();
		int[] arr1 = {
			8,
			2,
			0,
			6,
			-2,
			6,
			-1,
			9,
			4,
			3
		};
		int size = arr1.Length;
		obj.three_largest(arr1, size);
		int[] arr2 = {
			9,
			2,
			-7,
			4,
			1,
			3,
			7,
			22,
			8,
			-4
		};
		size = arr2.Length;
		obj.three_largest(arr2, size);
	}
}

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
<?php
/*
  Php Program
  Find three largest element in array
*/
class MyArray
{
	//Function which is display array elements
	function display( & $arr, $size)
	{
		$i = 0;
		while ($i < $size)
		{
			echo " ". $arr[$i] ." ";
			++$i;
		}
		echo "\n";
	}
	//Method which is finding the third largest element in given array
	function three_largest( & $arr, $size)
	{
		if ($size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		$first = -PHP_INT_MAX;
		$second = -PHP_INT_MAX;
		$third = -PHP_INT_MAX;
		$i = 0;
		while ($i < $size)
		{
			//Check if whether array element i value is largest than of variable first 
			if ($arr[$i] > $first)
			{
				//modify the value of all three variables
				$third = $second;
				$second = $first;
				//Assign a new big value
				$first = $arr[$i];
			}
			else if ($arr[$i] > $second)
			{
				//When get second largest element
				$third = $second;
				//Assign a new big value
				$second = $arr[$i];
			}
			else if ($arr[$i] > $third)
			{
				//When get third largest element
				$third = $arr[$i];
			}++$i;
		}
		$this->display($arr, $size);
		echo "Resultant largest\n";
		echo "first : ". $first ." second : ". $second ." third : ". $third ."\n\n";
	}
}

function main()
{
	$obj = new MyArray();
	//Define array elements
	$arr1 = array(8, 2, 0, 6, -2, 6, -1, 9, 4, 3);
	$size = count($arr1);
	$obj->three_largest($arr1, $size);
	//Define array elements
	$arr2 = array(9, 2, -7, 4, 1, 3, 7, 22, 8, -4);
	$size = count($arr2);
	$obj->three_largest($arr2, $size);
}
main();

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
/*
  Node Js Program
  Find three largest element in array
*/
class MyArray
{
	//Function which is display array elements
	display(arr, size)
	{
		var i = 0;
		while (i < size)
		{
			process.stdout.write(" " + arr[i] + " ");
			++i;
		}
		process.stdout.write("\n");
	}
	//Method which is finding the third largest element in given array
	three_largest(arr, size)
	{
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		var first = -Number.MAX_VALUE;
		var second = -Number.MAX_VALUE;
		var third = -Number.MAX_VALUE;
		var i = 0;
		while (i < size)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			{
				//like a swap operation of two variable
				//modify the value of all three variables
				third = second;
				second = first;
				//Assign a new big value
				first = arr[i];
			}
			else if (arr[i] > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr[i];
			}
			else if (arr[i] > third)
			{
				//When get third largest element
				third = arr[i];
			}
			++i;
		}
		this.display(arr, size);
		process.stdout.write("Resultant largest\n");
		process.stdout.write("first : " + first + " second : " + second + " third : " + third + "\n\n");
	}
}

function main()
{
	var obj = new MyArray();
	//Define array elements
	var arr1 = [8, 2, 0, 6, -2, 6, -1, 9, 4, 3];
	var size = arr1.length;
	obj.three_largest(arr1, size);
	//Define array elements
	var arr2 = [9, 2, -7, 4, 1, 3, 7, 22, 8, -4];
	size = arr2.length;
	obj.three_largest(arr2, size);
}
main();

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
#   Python 3 Program
#   Find three largest element in array

import sys

class MyArray :
	# Function which is display array elements
	def display(self, arr, size) :
		i = 0
		while (i < size) :
			print(" ", arr[i] ," ", end = "")
			i += 1
		
		print("\n", end = "")
	
	# Method which is finding the third largest element in given array
	def three_largest(self, arr, size) :
		if (size < 3) :
			return
		
		# initial set the minimum value of variables
		first = -sys.maxsize
		second = -sys.maxsize
		third = -sys.maxsize
		i = 0
		while (i < size) :
			# Check if whether array element i value is largest than of variable first 
			if (arr[i] > first) :
				# modify the value of all three variables
				# like a swap operation of two variable
				third = second
				second = first
				# Assign a new big value
				first = arr[i]
			
			elif(arr[i] > second) :
				# When get second largest element
				third = second
				# Assign a new big value
				second = arr[i]
			
			elif(arr[i] > third) :
				# When get third largest element
				third = arr[i]
			
			i += 1
		
		self.display(arr, size)
		print("Resultant largest\n", end = "")
		print("first : ", first ," second : ", second ," third : ", third ,"\n\n", end = "")
	

def main() :
	obj = MyArray()
	# Define array elements
	arr1 = [8, 2, 0, 6, -2, 6, -1, 9, 4, 3]
	size = len(arr1)
	obj.three_largest(arr1, size)
	# Define array elements
	arr2 = [9, 2, -7, 4, 1, 3, 7, 22, 8, -4]
	size = len(arr2)
	obj.three_largest(arr2, size)

if __name__ == "__main__": main()

Output

  8    2    0    6    -2    6    -1    9    4    3
Resultant largest
first :  9  second :  8  third :  6

  9    2    -7    4    1    3    7    22    8    -4
Resultant largest
first :  22  second :  9  third :  8
#   Ruby Program
#   Find three largest element in array

class MyArray

	# Function which is display array elements
	def display(arr, size)
	
		i = 0
		while (i < size)
		
			print(" ", arr[i] ," ")
			i += 1
		end
		print("\n")
	end
	# Method which is finding the third largest element in given array
	def three_largest(arr, size)
	
		if (size < 3)
		
			return
		end
		# initial set the minimum value of variables
		first = -(2 ** (0. size * 8 - 2))
		second = -(2 ** (0. size * 8 - 2))
		third = -(2 ** (0. size * 8 - 2))
		i = 0
		while (i < size)
		
			# Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			
				# modify the value of all three variables
				# like a swap operation of two variable
				third = second
				second = first
				# Assign a new big value
				first = arr[i]
			elsif(arr[i] > second)
			
				# When get second largest element
				third = second
				# Assign a new big value
				second = arr[i]
			elsif(arr[i] > third)
			
				# When get third largest element
				third = arr[i]
			end
			i += 1
		end
		self.display(arr, size)
		print("Resultant largest\n")
		print("first : ", first ," second : ", second ," third : ", third ,"\n\n")
	end
end
def main()

	obj = MyArray.new()
	# Define array elements
	arr1 = [8, 2, 0, 6, -2, 6, -1, 9, 4, 3]
	size = arr1.length
	obj.three_largest(arr1, size)
	# Define array elements
	arr2 = [9, 2, -7, 4, 1, 3, 7, 22, 8, -4]
	size = arr2.length
	obj.three_largest(arr2, size)
end
main()

Output

 8  2  0  6  -2  6  -1  9  4  3 
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4 
Resultant largest
first : 22 second : 9 third : 8

/*
  Scala Program
  Find three largest element in array
*/
class MyArray
{
	//Function which is display array elements
	def display(arr: Array[Int], size: Int): Unit = {
		var i: Int = 0;
		while (i < size)
		{
			print(" " + arr(i) + " ");
			i += 1;
		}
		print("\n");
	}
	//Method which is finding the third largest element in given array
	def three_largest(arr: Array[Int], size: Int): Unit = {
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		var first: Int = Int.MinValue;
		var second: Int = Int.MinValue;
		var third: Int = Int.MinValue;
		var i: Int = 0;
		while (i < size)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr(i) > first)
			{
				//modify the value of all three variables
				//like a swap operation of two variable
				third = second;
				second = first;
				//Assign a new big value
				first = arr(i);
			}
			else if (arr(i) > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr(i);
			}
			else if (arr(i) > third)
			{
				//When get third largest element
				third = arr(i);
			}
			i += 1;
		}
		display(arr, size);
		print("Resultant largest\n");
		print("first : " + first + " second : " + second + " third : " + third + "\n\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: MyArray = new MyArray();
		//Define array elements
		var arr1: Array[Int] = Array(8, 2, 0, 6, -2, 6, -1, 9, 4, 3);
		var size: Int = arr1.length;
		obj.three_largest(arr1, size);
		//Define array elements
		var arr2: Array[Int] = Array(9, 2, -7, 4, 1, 3, 7, 22, 8, -4);
		size = arr2.length;
		obj.three_largest(arr2, size);
	}
}

Output

 8  2  0  6  -2  6  -1  9  4  3
Resultant largest
first : 9 second : 8 third : 6

 9  2  -7  4  1  3  7  22  8  -4
Resultant largest
first : 22 second : 9 third : 8
/*
  Swift Program
  Find three largest element in array
*/
class MyArray
{
	//Function which is display array elements
	func display(_ arr: [Int], _ size: Int)
	{
		var i: Int = 0;
		while (i < size)
		{
			print(" ", arr[i] ," ", terminator: "");
			i += 1;
		}
		print("\n", terminator: "");
	}
	//Method which is finding the third largest element in given array
	func three_largest(_ arr: [Int], _ size: Int)
	{
		if (size < 3)
		{
			return;
		}
		//initial set the minimum value of variables
		var first: Int = Int.min;
		var second: Int = Int.min;
		var third: Int = Int.min;
		var i: Int = 0;
		while (i < size)
		{
			//Check if whether array element i value is largest than of variable first 
			if (arr[i] > first)
			{
				//modify the value of all three variables
				//like a swap operation of two variable
				third = second;
				second = first;
				//Assign a new big value
				first = arr[i];
			}
			else if (arr[i] > second)
			{
				//When get second largest element
				third = second;
				//Assign a new big value
				second = arr[i];
			}
			else if (arr[i] > third)
			{
				//When get third largest element
				third = arr[i];
			}
			i += 1;
		}
		self.display(arr, size);
		print("Resultant largest\n", terminator: "");
		print("first : ", first ," second : ", second ," third : ", third ,"\n\n", terminator: "");
	}
}
func main()
{
	let obj: MyArray = MyArray();
	//Define array elements
	let arr1: [Int] = [8, 2, 0, 6, -2, 6, -1, 9, 4, 3];
	var size: Int = arr1.count;
	obj.three_largest(arr1, size);
	//Define array elements
	let arr2: [Int] = [9, 2, -7, 4, 1, 3, 7, 22, 8, -4];
	size = arr2.count;
	obj.three_largest(arr2, size);
}
main();

Output

  8    2    0    6    -2    6    -1    9    4    3
Resultant largest
first :  9  second :  8  third :  6

  9    2    -7    4    1    3    7    22    8    -4
Resultant largest
first :  22  second :  9  third :  8

Time Complexity

The time complexity of this algorithm is O(n), where n is the size of the input array. This is because the algorithm iterates through the array once, performing constant time operations for each element.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment