Skip to content

Instantly share code, notes, and snippets.

@ApolloZhu
Created January 13, 2018 15:53
Show Gist options
  • Save ApolloZhu/ca2a7ec815af80e13ab6b5c3f1fe40af to your computer and use it in GitHub Desktop.
Save ApolloZhu/ca2a7ec815af80e13ab6b5c3f1fe40af to your computer and use it in GitHub Desktop.
Merge two sorted array into one in the same order
func mergeSorted<T:Comparable>(_ x: [T], _ y: [T], inOrder cmp: (T, T) -> Bool = (<) ) -> [T] {
var z = [T]()
var i = 0, j = 0
while i < x.count || j < y.count {
if j == y.count || cmp(x[i], y[j]) {
z.append(x[i])
i += 1
} else {
z.append(y[j])
j += 1
}
}
return z
}
let a, b: [Int]
a = [3,5,7,20,21]
// a = [5,3]
b = [1,7,9,11]
// b = [4]
print(mergeSorted(a,b))
// print(mergeSorted(a,b,inOrder: >))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment