Q : Finding second largest element in the array(PYTHON):
Approach 1:
First we define two variables large and sec_large and assign values 0 to them.
Next we iterate through the entire list and make sec_large to large and large to a number greater than large in the list .
def Second_largest(list):
largest = 0
sec_largest = 0
for item in list:
if largest < item:
sec_largest = largest
largest = item
return sec_largest
print(Second_largest([10,20,30,40,60]))
Approach 2:
First we sort the array in decsending order ,then return the second last element which is not equal to last.
def sec_large(arr):
if len(arr)<2:
return "No Second Element Exist."
else:
arr.sort() #sorting the array in descending order
for index in range(len(arr)-2,-1,-1): #iterating from second last to first element
if arr[index] != arr[len(arr)-1]: #checking which element is not equal to last
return arr[index]
else:
return "No Second Element Exist."
print(sec_large([2,5,3,6,6]))