Created
October 13, 2017 15:32
-
-
Save junyixin/62a67de8c1cf368548d15f1a2b23b2c6 to your computer and use it in GitHub Desktop.
归并排序(Swift)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array where Element: Comparable { | |
mutating func mergeSort(_ begin: Index, _ end: Index) { | |
var tmp: [Element] = [] | |
tmp.reserveCapacity(count) | |
//local function | |
func merge(_ begin: Index, _ mid: Index, _ end: Index) { | |
tmp.removeAll(keepingCapacity: true) | |
var i = begin | |
var j = mid | |
while i != mid && j != end { | |
if self[i] < self[j] { | |
tmp.append(self[i]) | |
i += 1 | |
} | |
else { | |
tmp.append(self[j]) | |
j += 1 | |
} | |
} | |
tmp.append(contentsOf: self[i..<mid]) | |
tmp.append(contentsOf: self[j..<end]) | |
replaceSubrange(begin..<end, with: tmp) | |
} | |
if (end - begin) > 1 { | |
let mid = (begin + end) / 2 | |
mergeSort(begin, mid) | |
mergeSort(mid, end) | |
//merge | |
merge(begin, mid, end) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment