find the kth smallest element in an array in swift

One way to find the kth smallest element in an array in Swift is to sort the array in ascending order and then access the element at index k-1. This assumes that k is a valid index in the sorted array.

Here's an implementation of this approach:

main.swift
func kthSmallestElement(_ array: [Int], k: Int) -> Int? {
    // Check that k is a valid index
    guard k > 0, k <= array.count else { return nil }
    
    // Sort the array in ascending order
    let sortedArray = array.sorted()
    
    // Return the element at index k-1
    return sortedArray[k-1]
}
306 chars
11 lines

You can use this function by passing in an array and the value of k:

main.swift
let myArray = [7, 2, 5, 1, 8, 9]
let k = 3

if let kthSmallest = kthSmallestElement(myArray, k: k) {
    print("The \(k)th smallest element in the array is \(kthSmallest)")
} else {
    print("Invalid value of k")
}
216 chars
9 lines

This will output:

main.swift
The 3rd smallest element in the array is 5
43 chars
2 lines

gistlibby LogSnag