forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.swift
40 lines (38 loc) · 1.5 KB
/
InsertionSort.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// Performs the Insertion sort algorithm to a given array
///
/// - Parameters:
/// - array: the array of elements to be sorted
/// - isOrderedBefore: returns true if the elements provided are in the corect order
/// - Returns: a sorted array containing the same elements
func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
guard array.count > 1 else { return array }
/// - sortedArray: copy the array to save stability
var sortedArray = array
for index in 1..<sortedArray.count {
var currentIndex = index
let temp = sortedArray[currentIndex]
while currentIndex > 0, isOrderedBefore(temp, sortedArray[currentIndex - 1]) {
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
currentIndex -= 1
}
sortedArray[currentIndex] = temp
}
return sortedArray
}
/// Performs the Insertion sort algorithm to a given array
///
/// - Parameter array: the array to be sorted, containing elements that conform to the Comparable protocol
/// - Returns: a sorted array containing the same elements
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
var sortedArray = array
for var index in 1..<sortedArray.count {
let temp = sortedArray[index]
while index > 0, temp < sortedArray[index - 1] {
sortedArray[index] = sortedArray[index - 1]
index -= 1
}
sortedArray[index] = temp
}
return sortedArray
}