Created
June 7, 2012 06:07
-
-
Save hantuo/2886827 to your computer and use it in GitHub Desktop.
merge
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
package main | |
import ( | |
"fmt" | |
) | |
func merge(a, b []int) (c []int) { | |
c = make([]int, len(a)+len(b)) | |
var i, j, k int | |
fmt.Println("a: ", a) | |
fmt.Println("b: ", b) | |
for i < len(a) && j < len(b) { | |
if a[i] <= b[j] { | |
c[k] = a[i] | |
i++ | |
} else { | |
c[k] = b[j] | |
j++ | |
} | |
k++ | |
fmt.Printf("k: %d, c: %v\n", k, c) | |
} | |
println(i) | |
println(j) | |
println(k) | |
if i == len(a) { | |
for ; j < len(b); j++ { | |
c[k] = b[j] | |
k++ | |
} | |
} | |
if j == len(b) { | |
for ; i < len(a); i++ { | |
c[k] = a[i] | |
k++ | |
} | |
} | |
return | |
} | |
func merge2(a, b []int) (c []int) { | |
c = make([]int, len(a)+len(b)) | |
for i, _ := range c { | |
if len(a) > 0 && (len(b) == 0 || a[0] < b[0]) { | |
c[i] = a[0] | |
a = a[1:] | |
} else { | |
c[i] = b[0] | |
b = b[1:] | |
} | |
} | |
return | |
} | |
func main() { | |
a := []int{1, 2, 5, 7, 9} | |
b := []int{1, 2, 3, 6} | |
c := merge2(a, b) | |
fmt.Println(c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment