find the kth smallest number in a list in swift

To find the kth smallest number in a list, one way is to first sort the list in ascending order, then return the element at index k-1.

Here's a simple implementation in Swift:

main.swift
func kthSmallest(_ array: [Int], _ k: Int) -> Int? {
    guard array.count >= k else {
        return nil // k is out of bounds
    }
    let sorted = array.sorted()
    return sorted[k-1]
}
191 chars
8 lines

Here's an example usage:

main.swift
let numbers = [3, 5, 2, 8, 1]
let k = 3 // find the 3rd smallest number
if let result = kthSmallest(numbers, k) {
    print(result) // output: 3
} else {
    print("k is out of bounds")
}
188 chars
8 lines

Note that the above implementation sorts the entire array, which has a time complexity of O(n log n) in the average case. There are more efficient algorithms for finding the kth smallest element, such as Quickselect, which has a time complexity of O(n) in the average case.

gistlibby LogSnag