# Swift Program to find the second largest element from the array

In Swift, we can find the second largest element from the given array using the sort() function or using user defined function. For example, we have the following array −

Array = [34, 23, 1, 45, 3]


Hence the largest element is 45 and the second largest element is 34. So lets discuss both the methods in detail along with examples.

## Method 1

In this method, we find the second largest element from the specified array by creating user defined function.

### Example

In the following example, we will create a function named as ‘secondlargestElement’, it takes an array as an argument and return the second largest element of the specified array. This function first sort the input array in the ascending order and, then return the second largest element from the end of the array. So to print the output we need to call the secondlargestElement() function and pass the array into it.

import Foundation
import Glibc

// Function to find second largest element from the array
func secondlargestElement(a:[Int])->Int{
var arr = a

for x in 0..<arr.count{
for y in x+1..<arr.count{
if (arr[x]>arr[y]) {
let t = arr[x]
arr[x] = arr[y]
arr[y] = t
}
}
}
return arr[arr.count-2]
}

// Test Array
var arr = [3, 4, 19, 4, 18, 3, 20, 3, 22]

print("Second Largest Element is", secondlargestElement(a:arr))


### Output

Second Largest Element is 20


## Method 2

In this method, we first sort the element of the array in descending order using sort(by:>) function and then find the second element of the array because the first element is the largest element and the second element of the array is the second largest element of the array.

### Example 2

In the following example, we will have an array of integer type. They we sort the array in the ascending order using sort(by:>) function. Now find the second element of the array because in the sorted array second element contains second largest element.

import Foundation
import Glibc

// Test case
var arr = [34, 10, 4, 9, 19, 45, 23, 87, 2, 4]

// Sort the array in descending order
arr.sort(by:>)

// Finding Second largest element
let result = arr
print("Second largest element is \(result)")


### Output

Second largest element is 45


## Conclusion

So this is how we can find the second largest element from the array. Both the methods provide the accurate result. These methods work for any data types like integer, float, double, etc with some minor changes.

Updated on: 06-Apr-2023

968 Views 