Quick sort algorithm in Swift

Asked on 08/04/2024

1 search

To implement the Quick Sort algorithm in Swift, you can leverage Swift's powerful features such as generics and functional programming. Below is an example of how you might write a Quick Sort function in Swift:

func quickSort<T: Comparable>(_ array: [T]) -> [T] {
    guard array.count > 1 else { return array }
    
    let pivot = array[array.count / 2]
    let less = array.filter { $0 < pivot }
    let equal = array.filter { $0 == pivot }
    let greater = array.filter { $0 > pivot }
    
    return quickSort(less) + equal + quickSort(greater)
}

// Example usage:
let unsortedArray = [3, 6, 8, 10, 1, 2, 1]
let sortedArray = quickSort(unsortedArray)
print(sortedArray) // Output: [1, 1, 2, 3, 6, 8, 10]

This implementation uses Swift's filter function to partition the array into elements less than, equal to, and greater than the pivot. It then recursively sorts the partitions and concatenates them to produce the sorted array.

For more information on Swift's collection algorithms and functional programming features, you might find the session A Swift Tour: Explore Swift’s features and design particularly useful. This session covers Swift's collection types and algorithms, which can help you understand how to use Swift's standard library to write efficient and elegant code.