Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stable Swift merge sort
extension Array where Element: Comparable
{
mutating func mergesortInPlace() {
var tmp: [Generator.Element] = []
tmp.reserveCapacity(numericCast(self.count))
func merge(lo: Int, _ mi: Int, _ hi: Int) {
tmp.removeAll(keepCapacity: true)
tmp.extend(self[lo..<hi])
var i = 0, var j = mi - lo
let imax = j, jmax = tmp.count
for k in lo..<hi {
if i == imax { self[k] = tmp[j++] }
else if j == jmax { self[k] = tmp[i++] }
else if tmp[j] < tmp[i] { self[k] = tmp[j++] }
else { self[k] = tmp[i++] }
}
}
let N = self.count
for var sz = 1 ; sz < N ; sz += sz {
for var lo = 0; lo < N-sz ; lo += sz + sz {
merge(lo, (lo+sz), min(lo+sz+sz,N))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.