|
| 1 | + |
| 2 | +import Foundation |
| 3 | + |
| 4 | +extension Array where Element: Comparable { |
| 5 | + |
| 6 | + mutating func mergeSort(by comparison: (Element, Element) -> Bool) { |
| 7 | + guard self.count > 1 else { |
| 8 | + return |
| 9 | + } |
| 10 | + _mergeSort(from: 0, to: count - 1, by: comparison) |
| 11 | + } |
| 12 | + |
| 13 | + mutating private func _mergeSort( |
| 14 | + from left: Int, |
| 15 | + to right: Int, |
| 16 | + by comparison: (Element, Element) -> Bool |
| 17 | + ) { |
| 18 | + if left < right { |
| 19 | + let mid = left + (right - left) / 2 |
| 20 | + _mergeSort(from: 0, to: mid, by: comparison) |
| 21 | + _mergeSort(from: mid + 1, to: right, by: comparison) |
| 22 | + _merge(from: left, mid: mid, to: right, by: comparison) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + mutating private func _merge( |
| 27 | + from left: Int, |
| 28 | + mid: Int, |
| 29 | + to right: Int, |
| 30 | + by comparison: (Element, Element) -> Bool |
| 31 | + ) { |
| 32 | + var copy = [Element](repeating: self[left], count: right - left + 1) |
| 33 | + var (leftStartIndex, rightStartIndex, currentIndex) = (left, mid + 1, 0) |
| 34 | + for _ in left ... right { |
| 35 | + if leftStartIndex > mid { |
| 36 | + copy[currentIndex] = self[rightStartIndex] |
| 37 | + rightStartIndex += 1 |
| 38 | + } else if rightStartIndex > right { |
| 39 | + copy[currentIndex] = self[leftStartIndex] |
| 40 | + leftStartIndex += 1 |
| 41 | + } else if comparison(self[leftStartIndex], self[rightStartIndex]) { |
| 42 | + copy[currentIndex] = self[leftStartIndex] |
| 43 | + leftStartIndex += 1 |
| 44 | + } else { |
| 45 | + copy[currentIndex] = self[rightStartIndex] |
| 46 | + rightStartIndex += 1 |
| 47 | + } |
| 48 | + currentIndex += 1 |
| 49 | + } |
| 50 | + leftStartIndex = left |
| 51 | + for i in copy.indices { |
| 52 | + self[leftStartIndex] = copy[i] |
| 53 | + leftStartIndex += 1 |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + func mergeSorted(by comparison: (Element, Element) -> Bool) -> Array { |
| 58 | + var copy = self |
| 59 | + copy.mergeSort(by: comparison) |
| 60 | + return copy |
| 61 | + } |
| 62 | + |
| 63 | +} |
| 64 | + |
| 65 | +// The code below can be used for testing |
| 66 | +// var numberList = [15, 2, 23, 11, 3, 9] |
| 67 | +// debugPrint(numberList.mergeSorted(by: >)) |
| 68 | +// numberList.mergeSort(by: <) |
| 69 | +// debugPrint(numberList) |
0 commit comments