Last active
December 22, 2015 17:31
-
-
Save telliott99/8b8bd7278a4ffca59812 to your computer and use it in GitHub Desktop.
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
func merge(a1: [Int], _ a2: [Int]) -> [Int] { | |
// a1 and a2 are sorted already | |
var ret: [Int] = [] | |
var i: Int = 0 | |
var j: Int = 0 | |
while i < a1.count || j < a2.count { | |
if j == a2.count { | |
if i == a1.count - 1 { | |
ret.append(a1[i]) | |
} | |
else { | |
ret += a1[i...a1.count-1] | |
} | |
break | |
} | |
if i == a1.count { | |
if j == a2.count - 1 { | |
ret.append(a2[j]) | |
} | |
else { | |
ret += a2[j...a2.count-1] | |
} | |
break | |
} | |
if a1[i] < a2[j] { | |
ret.append(a1[i]); i += 1 | |
} | |
else { | |
ret.append(a2[j]); j += 1 | |
} | |
} | |
return ret | |
} | |
func merge_sort(a: [Int]) -> [Int] { | |
if a.count == 1 { | |
return a | |
} | |
if a.count == 2 { | |
return merge([a[0]],[a[1]]) | |
} | |
let i = a.count/2 | |
let a1 = merge_sort(Array(a[0...i])) | |
let a2 = merge_sort(Array(a[i+1...a.count-1])) | |
return merge(a1, a2) | |
} | |
func pp (s: String, _ a: [Int]) { | |
print (s + " ") | |
for n in a { print("\(n) ", terminator: " ") } | |
print("") | |
} | |
let a = [32,7,100,29,55,3,19,82,23] | |
pp("before: ", a) | |
let m = merge_sort(a) | |
pp("merge : ", m) | |
/* | |
> swift test.swift | |
before: | |
32 7 100 29 55 3 19 82 23 | |
merge : | |
3 7 19 23 29 32 55 82 100 | |
> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment