|
1 |
| -//: Playground - noun: a place where people can play |
2 |
| - |
3 | 1 | /// Performs the Insertion sort algorithm to a given array
|
4 | 2 | ///
|
5 | 3 | /// - Parameters:
|
6 | 4 | /// - array: the array of elements to be sorted
|
7 |
| -/// - isOrderedBefore: returns true if the elements provided are in the corect order |
| 5 | +/// - isOrderedBefore: function that given to inputs returns whether should be order before or after. Allows for different sorts (e.g. change in direction). |
8 | 6 | /// - Returns: a sorted array containing the same elements
|
9 | 7 | func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
|
10 | 8 | guard array.count > 1 else { return array }
|
11 |
| - |
12 |
| - var a = array |
13 |
| - for x in 1..<a.count { |
14 |
| - var y = x |
15 |
| - let temp = a[y] |
16 |
| - while y > 0 && isOrderedBefore(temp, a[y - 1]) { |
17 |
| - a[y] = a[y - 1] |
18 |
| - y -= 1 |
| 9 | + var sortedArray = array |
| 10 | + for index in 1..<sortedArray.count { |
| 11 | + if isOrderedBefore(sortedArray[index-1], sortedArray[index]) { continue } |
| 12 | + for currentIndex in (0..<index).reversed() { |
| 13 | + if isOrderedBefore(sortedArray[currentIndex], sortedArray[index]) { |
| 14 | + sortedArray.move(from: index, to: currentIndex + 1) |
| 15 | + break |
| 16 | + } else if currentIndex == 0 { |
| 17 | + sortedArray.move(from: index, to: 0) |
| 18 | + } |
19 | 19 | }
|
20 |
| - a[y] = temp |
21 | 20 | }
|
22 |
| - return a |
| 21 | + return sortedArray |
23 | 22 | }
|
24 | 23 |
|
25 | 24 | /// Performs the Insertion sort algorithm to a given array
|
26 | 25 | ///
|
27 |
| -/// - Parameter array: the array to be sorted, conatining elements that conform to the Comparable protocol |
28 |
| -/// - Returns: a sorted array containing the same elements |
| 26 | +/// - Parameter array: the array to be sorted, containing elements that conform to the Comparable protocol |
| 27 | +/// - Returns: a sorted array containing the same elements ordered from lowest to highest |
29 | 28 | func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
|
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 |
37 |
| - } |
38 |
| - a[y] = temp |
| 29 | + return insertionSort(array, <) |
| 30 | +} |
| 31 | + |
| 32 | +fileprivate extension Array { |
| 33 | + mutating func move(from: Int, to: Int) { |
| 34 | + let removed = self[from] |
| 35 | + self.remove(at: from) |
| 36 | + self.insert(removed, at: to) |
39 | 37 | }
|
40 |
| - return a |
41 | 38 | }
|
42 | 39 |
|
43 | 40 | let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
|
|
0 commit comments