You are given an unsorted array with n integers. You need to find the third largest integer in the array and print the value. Example: array = [5, 8, 2, 15, 6, 25, 1, 11, 13] Output: 13 array = [9, 3, 14, 22, 1, -6, 18, 15] Output: 15 array = [1, 1, 1, 1, 1] Output: Invalid array = [5, 2] Output: Invalid
Answers
Answer:
def get_third_largest(array):
// this iterates through all the numbers in array 3 times.
for i in range(2):
largest_val = float('-inf')
for val in array:
if val > largest_val:
largest_val = val
// this iterates through the array the third time
largest_val = float('-inf')
for val in array:
if val > largest_val:
largest_val = val
if largest_val == float('-inf'):
largest_val = "invalid"
print(largest_val)
Explanation:
First of all, I wrote the code above just for you, so you're welcome.
Secondly, there is a lot to it.
What it does is that it iterates through the array 2 times (removing the largest value each time) then the third time it prints the largest value.
But, if the largest value is still float('-inf') otherwise negative of infinity, it will automatically print 'invalid'.
Note: There are shorter ways to do this. If you want you can use a python built-in function that allows you to find the largest value in an array, because I did mine explicitly which makes it kind of longer.
Thank you, and please vote me as Brainliest.