2
2
///
3
3
/// - Parameters:
4
4
/// - array: the array of elements to be sorted
5
+ /// - sortedArray: copy the array to save stability
5
6
/// - isOrderedBefore: returns true if the elements provided are in the corect order
6
7
/// - Returns: a sorted array containing the same elements
7
8
func insertionSort< T> ( _ array: [ T ] , _ isOrderedBefore: ( T , T ) -> Bool ) -> [ T ] {
8
- guard array. count > 1 else { return array }
9
-
10
- var a = array
11
- for x in 1 ..< a. count {
12
- var y = x
13
- let temp = a [ y]
14
- while y > 0 && isOrderedBefore ( temp, a [ y - 1 ] ) {
15
- a [ y] = a [ y - 1 ]
16
- y -= 1
9
+ guard array. count > 1 else { return array }
10
+ var sortedArray = array
11
+ for index in 1 ..< sortedArray. count {
12
+ var currentIndex = index
13
+ let temp = sortedArray [ currentIndex]
14
+ while currentIndex > 0 , isOrderedBefore ( temp, sortedArray [ currentIndex - 1 ] ) {
15
+ sortedArray [ currentIndex] = sortedArray [ currentIndex - 1 ]
16
+ currentIndex -= 1
17
+ }
18
+ sortedArray [ currentIndex] = temp
17
19
}
18
- a [ y] = temp
19
- }
20
- return a
20
+ return sortedArray
21
21
}
22
22
23
23
/// Performs the Insertion sort algorithm to a given array
@@ -27,15 +27,15 @@ func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
27
27
func insertionSort< T: Comparable > ( _ array: [ T ] ) -> [ T ] {
28
28
guard array. count > 1 else { return array }
29
29
30
- var a = array
31
- for x in 1 ..< a . count {
32
- var y = x
33
- let temp = a [ y ]
34
- while y > 0 && temp < a [ y - 1 ] {
35
- a [ y ] = a [ y - 1 ]
36
- y -= 1
30
+ var sortedArray = array
31
+ for index in 1 ..< sortedArray . count {
32
+ var currentIndex = index
33
+ let temp = sortedArray [ currentIndex ]
34
+ while currentIndex > 0 , temp < sortedArray [ currentIndex - 1 ] {
35
+ sortedArray [ currentIndex ] = sortedArray [ currentIndex - 1 ]
36
+ currentIndex -= 1
37
37
}
38
- a [ y ] = temp
38
+ sortedArray [ currentIndex ] = temp
39
39
}
40
- return a
40
+ return sortedArray
41
41
}
0 commit comments