find the kth largest number in a list in swift

To find the kth largest number in a list in Swift, one approach is to sort the array in descending order and return the element at index k-1. Here's an implementation of this approach:

main.swift
func kthLargestNumber(_ arr: [Int], _ k: Int) -> Int? {
    guard k > 0 && k <= arr.count else {
        return nil // invalid input
    }
    let sortedArr = arr.sorted(by: >) // sort array in descending order
    return sortedArr[k - 1] // return kth largest number
}
270 chars
8 lines

You can use this function as follows:

main.swift
let arr = [3, 2, 1, 5, 4]
if let kthLargest = kthLargestNumber(arr, 3) {
    print("The 3rd largest number in \(arr) is \(kthLargest)") // prints "The 3rd largest number in [3, 2, 1, 5, 4] is 3"
} else {
    print("Invalid input") // prints "Invalid input"
}
259 chars
7 lines

Note that the function returns an optional, as the input might be invalid (if k is out of range).

gistlibby LogSnag