find the kth largest element in an array in swift

To find the kth largest element in an array in Swift, we can sort the array in descending order and then return the element at index k-1. Here's the code to do that:

main.swift
func findKthLargestElement(in array: [Int], k: Int) -> Int? {
    guard k > 0 && k <= array.count else {
        return nil
    }
    
    let sortedArray = array.sorted(by: >)
    let kthLargest = sortedArray[k-1]
    return kthLargest
}

// Example usage:
let array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
let k = 3
if let kthLargest = findKthLargestElement(in: array, k: k) {
    print("The \(k)th largest element is \(kthLargest)")
} else {
    print("Invalid input")
}
467 chars
19 lines

In the above code, we first check if k is a valid value (i.e. greater than 0 and less than or equal to the size of the array). If it's not valid, we return nil.

Next, we sort the array in descending order using the sorted(by:) function with the > operator as the sorting criteria.

Finally, we return the kth largest element at index k-1 (since arrays are 0-indexed).

To test the function, we create an example array and call the findKthLargestElement function with a value of k=3. The output should be "The 3rd largest element is 5".

gistlibby LogSnag