Selection Sort in Swift
Selection Sort in Swift
Selection Sort is an in-place comparison sorting algorithm. It divides the input list into two parts: a sorted sublist of items which is built up from left to right, and a sublist of the remaining unsorted items. The algorithm repeatedly finds the minimum element from the unsorted sublist and swaps it with the leftmost unsorted element.
Implementation in Swift
Here is the implementation of Selection Sort in Swift as an extension on the Array type.
extension Array where Element: Comparable {
mutating func selectionSort() {
guard count > 1 else { return }
for i in 0..<count - 1 {
var minIndex = i
for j in (i + 1)..<count {
if self[j] < self[minIndex] {
minIndex = j
}
}
if minIndex != i {
self.swapAt(i, minIndex)
}
}
}
func selectionSorted() -> [Element] {
var result = self
result.selectionSort()
return result
}
}
// Example usage:
var numbers = [64, 25, 12, 22, 11]
numbers.selectionSort()
print("Sorted array: \(numbers)")
// Output: Sorted array: [11, 12, 22, 25, 64]
Complexity Analysis
- Time Complexity:
- Best Case: because we always run the nested loops.
- Average Case: when elements are in random order.
- Worst Case: when elements are sorted in reverse order.
- Space Complexity: auxiliary space because it sorts the array in-place.
Track Your Progress
Done with this topic? Mark it as complete to track your progress.
💬 Discuss this page
Have a question or spot something confusing in "Selection Sort in Swift"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.