Skip to main content

Find third largest number in array

In this article, we will discuss the problem of finding the third largest number in an array. We'll explore a simple and efficient approach to solve this problem, and provide a step-by-step explanation of the algorithm. We'll also analyze the time complexity of the algorithm and provide a detailed explanation of the provided code example. By the end of this article, you will have a clear understanding of how to find the third largest number in an array and the reasoning behind each step.

Problem Statement

Given an array of integers, we are tasked with finding the third largest number present in the array. For example, consider the array [7, 1, 8, 3, 12, 13, -3, 6, 31, 62]. The third largest number in this array is 13.

Solution Idea

To solve this problem, we can follow a simple approach that involves iterating through the array while maintaining three variables to keep track of the top three largest elements encountered so far. We will initialize these variables with initial values that indicate an absence of elements. As we iterate through the array, we will update these variables based on the values encountered.

Standard Pseudocode

Here is the pseudocode that outlines the approach to find the third largest element in an array:

function findThirdLargest(arr):
    if size of arr < 3:
        return "Array size is too small"
    
    Initialize first = INT_MIN
    Initialize second = INT_MIN
    Initialize third = INT_MIN
    
    for each 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
    
    return third

Algorithm Explanation

  1. We first check if the size of the array is less than 3. If it is, then we return a message indicating that the array size is too small to find the third largest element.

  2. We initialize three variables, first, second, and third, with values INT_MIN (negative infinity) to indicate that we haven't encountered any valid element yet.

  3. We iterate through the array and for each element, we compare it with the values of first, second, and third.

  4. If the element is greater than the current first, we update all three variables: third becomes second, second becomes first, and first becomes the current element.

  5. If the element is not greater than first but is greater than second, we update third to the value of second and second to the current element.

  6. If the element is not greater than both first and second but is greater than third, we update third to the value of the current element.

  7. After iterating through the entire array, the value of third will hold the third largest element.

  8. We return the value of third as the result.

Code Solution

// C Program
// Find third largest number 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 thirdLargest(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 elements of given array
    display(arr, size);
    // Display result
    printf("Third Largest : %d\n\n", third);
}
int main()
{
    //Define array elements
    int arr1[] = {
        1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11
    };
    int arr2[] = {
        7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62
    };
    // Test A
    int size = sizeof(arr1) / sizeof(arr1[0]);
    // arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
    //                        ↑      ↑           ↑     
    //                        ➀     ➂           ➁    
    thirdLargest(arr1, size);
    // Test B 
    size = sizeof(arr2) / sizeof(arr2[0]);
    // arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
    //                            ↑             ↑    ↑
    //                            ➂            ➁    ➀ 
    thirdLargest(arr2, size);
    return 0;
}

Output

1 8 2 5 17 7 9 4 3 11
Third Largest : 9

7 1 8 3 12 13 -3 6 31 62
Third Largest : 13
// Java program
// Find third largest number in array

public class LargestNumber
{
    // 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 thirdLargest(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 elements of given array
        display(arr, size);
        // Display result
        System.out.print("Third Largest : " + third + "\n\n");
    }
    public static void main(String[] args)
    {
        LargestNumber task = new LargestNumber();

        //Define array elements
        int[] arr1 =  {
            1 , 8 , 2 , 5 , 17 , 7 , 9 , 4 , 3 , 11
        };
        int[] arr2 =  {
            7 , 1 , 8 , 3 , 12 , 13 , -3 , 6 , 31 , 62
        };
        // Test A
        int size = arr1.length;
        // arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
        //                        ↑      ↑           ↑     
        //                        ➀     ➂           ➁    
        task.thirdLargest(arr1, size);
        // Test B 
        size = arr2.length;
        // arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
        //                            ↑             ↑    ↑
        //                            ➂            ➁    ➀ 
        task.thirdLargest(arr2, size);
    }
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
// Include header file
#include <iostream>
#include <limits.h>

using namespace std;
// C++ program
// Find third largest number in array
class LargestNumber
{
	public:
		// Function which is display array elements
		void display(int arr[], int size)
		{
			for (int i = 0; i < size; ++i)
			{
				cout << "  " << arr[i];
			}
			cout << "\n";
		}
	// Method which is finding the third largest element in given array
	void thirdLargest(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 elements of given array
		this->display(arr, size);
		// Display result
		cout << "Third Largest : " << third << "\n\n";
	}
};
int main()
{
	LargestNumber *task = new LargestNumber();
	//Define array elements
	int arr1[] = {
		1 , 8 , 2 , 5 , 17 , 7 , 9 , 4 , 3 , 11
	};
	int arr2[] = {
		7 , 1 , 8 , 3 , 12 , 13 , -3 , 6 , 31 , 62
	};
	// Test A
	int size = sizeof(arr1) / sizeof(arr1[0]);
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀     ➂           ➁    
	task->thirdLargest(arr1, size);
	// Test B 
	size = sizeof(arr2) / sizeof(arr2[0]);
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	task->thirdLargest(arr2, size);
	return 0;
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
// Include namespace system
using System;
// Csharp program
// Find third largest number in array
public class LargestNumber
{
	// Function which is display array elements
	public void display(int[] arr, int size)
	{
		for (int i = 0; i < size; ++i)
		{
			Console.Write("  " + arr[i]);
		}
		Console.Write("\n");
	}
	// Method which is finding the third largest element in given array
	public void thirdLargest(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;
		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 elements of given array
		this.display(arr, size);
		// Display result
		Console.Write("Third Largest : " + third + "\n\n");
	}
	public static void Main(String[] args)
	{
		LargestNumber task = new LargestNumber();
		//Define array elements
		int[] arr1 = {
			1 , 8 , 2 , 5 , 17 , 7 , 9 , 4 , 3 , 11
		};
		int[] arr2 = {
			7 , 1 , 8 , 3 , 12 , 13 , -3 , 6 , 31 , 62
		};
		// Test A
		int size = arr1.Length;
		// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
		//                        ↑      ↑           ↑     
		//                        ➀     ➂           ➁    
		task.thirdLargest(arr1, size);
		// Test B 
		size = arr2.Length;
		// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
		//                            ↑             ↑    ↑
		//                            ➂            ➁    ➀ 
		task.thirdLargest(arr2, size);
	}
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
package main
import "math"
import "fmt"
// Go program
// Find third largest number in array
type LargestNumber struct {}
func getLargestNumber() * LargestNumber {
	var me *LargestNumber = &LargestNumber {}
	return me
}
// Function which is display array elements
func(this LargestNumber) display(arr[] int, size int) {
	for i := 0 ; i < size ; i++ {
		fmt.Print("  ", arr[i])
	}
	fmt.Print("\n")
}
// Method which is finding the third largest element in given array
func(this LargestNumber) thirdLargest(arr[] int, size int) {
	if size < 3 {
		return
	}
	// initial set the minimum value of variables
	var first int = math.MinInt64
	var second int = math.MinInt64
	var third int = math.MinInt64
	for 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 elements of given array
	this.display(arr, size)
	// Display result
	fmt.Print("Third Largest : ", third, "\n\n")
}
func main() {
	var task * LargestNumber = getLargestNumber()
	//Define array elements
	var arr1 = [] int {
		1,
		8,
		2,
		5,
		17,
		7,
		9,
		4,
		3,
		11
	}
	var arr2 = [] int {
		7,
		1,
		8,
		3,
		12,
		13,
		-3,
		6,
		31,
		62
	}
	// Test A
	var size int = len(arr1)
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀     ➂           ➁    
	task.thirdLargest(arr1, size)
	// Test B 
	size = len(arr2)
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	task.thirdLargest(arr2, size)
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
<?php
// Php program
// Find third largest number in array
class LargestNumber
{
	// Function which is display array elements
	public	function display($arr, $size)
	{
		for ($i = 0; $i < $size; ++$i)
		{
			echo("  ".$arr[$i]);
		}
		echo("\n");
	}
	// Method which is finding the third largest element in given array
	public	function thirdLargest($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;
		for ($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 elements of given array
		$this->display($arr, $size);
		// Display result
		echo("Third Largest : ".$third.
			"\n\n");
	}
}

function main()
{
	$task = new LargestNumber();
	//Define array elements
	$arr1 = array(1, 8, 2, 5, 17, 7, 9, 4, 3, 11);
	$arr2 = array(7, 1, 8, 3, 12, 13, -3, 6, 31, 62);
	// Test A
	$size = count($arr1);
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀      ➂          ➁    
	$task->thirdLargest($arr1, $size);
	// Test B 
	$size = count($arr2);
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	$task->thirdLargest($arr2, $size);
}
main();

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
// Node JS program
// Find third largest number in array
class LargestNumber
{
	// Function which is display array elements
	display(arr, size)
	{
		for (var i = 0; i < size; ++i)
		{
			process.stdout.write("  " + arr[i]);
		}
		process.stdout.write("\n");
	}
	// Method which is finding the third largest element in given array
	thirdLargest(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;
		for (var 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 elements of given array
		this.display(arr, size);
		// Display result
		process.stdout.write("Third Largest : " + third + "\n\n");
	}
}

function main()
{
	var task = new LargestNumber();
	//Define array elements
	var arr1 = [1, 8, 2, 5, 17, 7, 9, 4, 3, 11];
	var arr2 = [7, 1, 8, 3, 12, 13, -3, 6, 31, 62];
	// Test A
	var size = arr1.length;
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀     ➂           ➁    
	task.thirdLargest(arr1, size);
	// Test B 
	size = arr2.length;
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	task.thirdLargest(arr2, size);
}
main();

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
import sys
#  Python 3 program
#  Find third largest number in array
class LargestNumber :
	#  Function which is display list elements
	def display(self, arr, size) :
		i = 0
		while (i < size) :
			print("  ", arr[i], end = "")
			i += 1
		
		print(end = "\n")
	
	#  Method which is finding the third largest element in given list
	def thirdLargest(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 list 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
		
		#  Display elements of given list
		self.display(arr, size)
		#  Display result
		print("Third Largest : ", third ,"\n")
	

def main() :
	task = LargestNumber()
	# Define list elements
	arr1 = [1, 8, 2, 5, 17, 7, 9, 4, 3, 11]
	arr2 = [7, 1, 8, 3, 12, 13, -3, 6, 31, 62]
	#  Test A
	size = len(arr1)
	#  arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	#                         ↑      ↑           ↑     
	#                         ➀     ➂           ➁    
	task.thirdLargest(arr1, size)
	#  Test B 
	size = len(arr2)
	#  arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	#                             ↑             ↑    ↑
	#                             ➂            ➁    ➀ 
	task.thirdLargest(arr2, size)

if __name__ == "__main__": main()

Output

   1   8   2   5   17   7   9   4   3   11
Third Largest :  9

   7   1   8   3   12   13   -3   6   31   62
Third Largest :  13
#  Ruby program
#  Find third largest number in array
class LargestNumber 
	#  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 thirdLargest(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

		#  Display elements of given array
		self.display(arr, size)
		#  Display result
		print("Third Largest : ", third ,"\n\n")
	end

end

def main() 
	task = LargestNumber.new()
	# Define array elements
	arr1 = [1, 8, 2, 5, 17, 7, 9, 4, 3, 11]
	arr2 = [7, 1, 8, 3, 12, 13, -3, 6, 31, 62]
	#  Test A
	size = arr1.length
	#  arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	#                         ↑      ↑           ↑     
	#                         ➀     ➂           ➁    
	task.thirdLargest(arr1, size)
	#  Test B 
	size = arr2.length
	#  arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	#                             ↑             ↑    ↑
	#                             ➂            ➁    ➀ 
	task.thirdLargest(arr2, size)
end

main()

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13

// Scala program
// Find third largest number in array
class LargestNumber()
{
	// 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 thirdLargest(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 elements of given array
		display(arr, size);
		// Display result
		print("Third Largest : " + third + "\n\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: LargestNumber = new LargestNumber();
		//Define array elements
		var arr1: Array[Int] = Array(1, 8, 2, 5, 17, 7, 9, 4, 3, 11);
		var arr2: Array[Int] = Array(7, 1, 8, 3, 12, 13, -3, 6, 31, 62);
		// Test A
		var size: Int = arr1.length;
		// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
		//                        ↑      ↑           ↑     
		//                        ➀     ➂           ➁    
		task.thirdLargest(arr1, size);
		// Test B 
		size = arr2.length;
		// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
		//                            ↑             ↑    ↑
		//                            ➂            ➁    ➀ 
		task.thirdLargest(arr2, size);
	}
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13
import Foundation;
// Swift 4 program
// Find third largest number in array
class LargestNumber
{
	// 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(terminator: "\n");
	}
	// Method which is finding the third largest element in given array
	func thirdLargest(_ 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;
		}
		// Display elements of given array
		self.display(arr, size);
		// Display result
		print("Third Largest : ", third ,"\n");
	}
}
func main()
{
	let task: LargestNumber = LargestNumber();
	//Define array elements
	let arr1: [Int] = [1, 8, 2, 5, 17, 7, 9, 4, 3, 11];
	let arr2: [Int] = [7, 1, 8, 3, 12, 13, -3, 6, 31, 62];
	// Test A
	var size: Int = arr1.count;
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀     ➂           ➁    
	task.thirdLargest(arr1, size);
	// Test B 
	size = arr2.count;
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	task.thirdLargest(arr2, size);
}
main();

Output

   1   8   2   5   17   7   9   4   3   11
Third Largest :  9

   7   1   8   3   12   13   -3   6   31   62
Third Largest :  13
// Kotlin program
// Find third largest number in array
class LargestNumber
{
	// Function which is display array elements
	fun 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
	fun thirdLargest(arr: Array < Int > , size: Int): Unit
	{
		if (size < 3)
		{
			return;
		}
		// initial set the minimum value of variables
		var first: Int = Int.MIN_VALUE;
		var second: Int = Int.MIN_VALUE;
		var third: Int = Int.MIN_VALUE;
		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 elements of given array
		this.display(arr, size);
		// Display result
		print("Third Largest : " + third + "\n\n");
	}
}
fun main(args: Array < String > ): Unit
{
	val task: LargestNumber = LargestNumber();
	//Define array elements
	val arr1: Array < Int > = arrayOf(1, 8, 2, 5, 17, 7, 9, 4, 3, 11);
	val arr2: Array < Int > = arrayOf(7, 1, 8, 3, 12, 13, -3, 6, 31, 62);
	// Test A
	var size: Int = arr1.count();
	// arr = [1 , 8 , 2 , 5 ,17, 7 , 9 , 4 , 3 , 11]
	//                        ↑      ↑           ↑     
	//                        ➀     ➂           ➁    
	task.thirdLargest(arr1, size);
	// Test B 
	size = arr2.count();
	// arr = [7 , 1 , 8 , 3 , 12, 13 , -3 , 6 , 31 , 62]
	//                            ↑             ↑    ↑
	//                            ➂            ➁    ➀ 
	task.thirdLargest(arr2, size);
}

Output

  1  8  2  5  17  7  9  4  3  11
Third Largest : 9

  7  1  8  3  12  13  -3  6  31  62
Third Largest : 13

Resultant Output Explanation

Let's take the example arrays from the code:

  1. arr1 = [1, 8, 2, 5, 17, 7, 9, 4, 3, 11]

    • Third largest: 9
    • Output: 1 8 2 5 17 7 9 4 3 11 Third Largest : 9
  2. arr2 = [7, 1, 8, 3, 12, 13, -3, 6, 31, 62]

    • Third largest: 13
    • Output: 7 1 8 3 12 13 -3 6 31 62 Third Largest : 13

The program correctly identifies the third largest element in each array and displays the expected output.

Time Complexity Analysis

The time complexity of this algorithm is linear, O(n), where n is the size of the input array. This is because we iterate through the entire array once to determine the third largest element. The comparisons and updates in each iteration take constant time.





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