How to write a Python program to find the third-largest number in an array?
How to print the third largest element in an array?
Initially locate the biggest element, followed by the second largest element, and afterward barring them both locate the third-biggest component. Repeat the array iteration twice and mark the greatest and second biggest component and afterward barring them both locate the third greatest component, i.e the maximum element barring the greatest and second most greatest from the array.
What is the third-largest element in an array?
Input: array elements = [10,20,30,40,50]
Output: Third largest element is 30
Algorithm to find the third largest element in an array:
- Begin with iterating through the array and find the maximum element.
- Store the maximum element in a variable.
- Iterate again the whole array and find the second most maximum element.
- Lastly, iterate the array once again except the first and the second most maximum element to find the third most maximum element.
Python program to print the third largest element in an array.
import sys from array import * arr = array('i', []) n = int(input("enter number of elements")) for i in range(n): arr.append(int(input("enter the array elements"))) print("entered array is:") for i in range(len(arr)): print(arr[i]) def thirdLargest(arr, arr_size): if (arr_size < 3): print(" Please enter array size greater than 3 ") return first = arr[0] for i in range(1, arr_size): if (arr[i] > first): first = arr[i] second = -sys.maxsize for i in range(0, arr_size): if (arr[i] > second and arr[i] < first): second = arr[i] third = -sys.maxsize for i in range(0, arr_size): if (arr[i] > third and arr[i] < second): third = arr[i] print("The Third Largest", "element is", third) thirdLargest(arr, n)
Output: Printing the third largest element in an array