Insertion Sort in Swift
Insertion Sort in Swift
Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
Implementation in Swift
Here is the implementation of Insertion Sort in Swift as an extension on the Array type.
extension Array where Element: Comparable {
mutating func insertionSort() {
guard count > 1 else { return }
for i in 1..<count {
let key = self[i]
var j = i - 1
while j >= 0 && self[j] > key {
self[j + 1] = self[j]
j -= 1
}
self[j + 1] = key
}
}
func insertionSorted() -> [Element] {
var result = self
result.insertionSort()
return result
}
}
// Example usage:
var numbers = [12, 11, 13, 5, 6]
numbers.insertionSort()
print("Sorted array: \(numbers)")
// Output: Sorted array: [5, 6, 11, 12, 13]
Complexity Analysis
- Time Complexity:
- Best Case: when the array is already sorted.
- Average Case: when elements are in random order.
- Worst Case: when elements are sorted in reverse order.
- Space Complexity: auxiliary space.
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 "Insertion Sort in Swift"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.