From 422b1a59bd157e0095b2b26086024857bf6aca7b Mon Sep 17 00:00:00 2001 From: Wenru Dong Date: Tue, 16 Oct 2018 22:25:52 +0100 Subject: [PATCH] mergeSort in swift --- swift/12_sorts/.DS_Store | Bin 0 -> 6148 bytes swift/12_sorts/SortsTests.swift | 44 ++++++++++++++++++++++++++ swift/12_sorts/mergeSort.swift | 54 ++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 swift/12_sorts/.DS_Store create mode 100644 swift/12_sorts/SortsTests.swift create mode 100644 swift/12_sorts/mergeSort.swift diff --git a/swift/12_sorts/.DS_Store b/swift/12_sorts/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0(_ a: inout T) where T: RandomAccessCollection, T: MutableCollection, T.Element: Comparable { + mergeSort(&a, from: a.startIndex, to: a.index(before: a.endIndex)) +} + +fileprivate func mergeSort(_ a: inout T, from low: T.Index, to high: T.Index) where T: RandomAccessCollection, T: MutableCollection, T.Element: Comparable { + if low >= high { return } + let dist = a.distance(from: low, to: high) + let mid = a.index(low, offsetBy: dist/2) + mergeSort(&a, from: low, to: mid) + mergeSort(&a, from: a.index(mid, offsetBy: 1), to: high) + print(a) + merge(&a, from: low, through: mid, to: high) +} + +fileprivate func merge(_ a: inout T, from low: T.Index, through mid: T.Index, to high: T.Index) where T: RandomAccessCollection, T: MutableCollection, T.Element: Comparable { + var i = low + var j = a.index(mid, offsetBy: 1) + var tmp = Array() + tmp.reserveCapacity(a.distance(from: low, to: high) + 1) + while i <= mid && j <= high { + if a[i] <= a[j] { + tmp.append(a[i]) + a.formIndex(after: &i) + } else { + tmp.append(a[j]) + a.formIndex(after: &j) + } + } + + var start = i + var end = mid + if j <= high { + start = j + end = high + } + tmp.append(contentsOf: a[start...end]) + + var current = low + for element in tmp { + a[current] = element + print(element) + a.formIndex(after: ¤t) + } +}