Quick Sort in Swift
Quick Sort in Swift
Quick Sort is an efficient, comparison-based, divide-and-conquer sorting algorithm. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot.
Implementation in Swift
Here is a straightforward and readable implementation of Quick Sort 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 numbers = [10, 7, 8, 9, 1, 5]
let sortedNumbers = quickSort(numbers)
print("Sorted array: \(sortedNumbers)")
// Output: Sorted array: [1, 5, 7, 8, 9, 10]
Complexity Analysis
- Time Complexity:
- Best Case: when the partition process always divides the array into two nearly equal halves.
- Average Case: when partitions are reasonably balanced.
- Worst Case: when the partition process always divides the array into one element and elements (e.g., choosing the minimum/maximum element as the pivot).
- Space Complexity: in this implementation due to the sub-array allocations (a standard in-place implementation has call stack space).
Telemetry Integration
Completed working through this block? Sync progress to workspace.