stothers algorithm in swift

Here is an implementation of the quicksort algorithm in Swift using the Divide and Conquer methodology:

main.swift
func quickSort(_ input: [Int]) -> [Int] {
    guard input.count > 1 else { return input }
    
    let pivot = input[input.count/2]
    let less = input.filter { $0 < pivot }
    let equal = input.filter { $0 == pivot }
    let greater = input.filter { $0 > pivot }
    
    return quickSort(less) + equal + quickSort(greater)
}
329 chars
11 lines

This implementation first checks if the input array has only one or fewer elements. In these cases, it can be considered sorted and returned as is.

Next, the pivot is defined as the middle element of the input array. This could be any element of the array, but choosing one closer to the middle will generally improve performance.

The input array is then divided into three separate arrays: less, equal, and greater based on whether each element is less than, equal to, or greater than the pivot. These three arrays are recursively passed through the same quickSort function and eventually returned in sorted order.

One important thing to consider is that there are cases where quicksort can run into some performance problems, particularly in large lists, pathological cases, or when the partition element is not picked randomly.

gistlibby LogSnag