Skip to content

Commit

Permalink
add two sorted array
Browse files Browse the repository at this point in the history
  • Loading branch information
Nishi Davidson authored and Nishi Davidson committed Apr 2, 2020
1 parent d132235 commit 06e60bb
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions two-sorted-arrs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"fmt"
)

func main() {

k_sorted_arrs := [][]int{
[]int{1, 2, 5},
[]int{3, 6, 9, 12, 31},
}

fmt.Println(MergeKSortedArrs(k_sorted_arrs))

}

func MergeSortedArrs(k_sorted_arrs [][]int) []int {

k0 := &k_sorted_arrs[0]
k1 := &k_sorted_arrs[1]
temp_elems := []int{}
out := []int{}
i, j := 0, 0

l := len(*k0) + len(*k1)

for l > 0 {
temp_elems = append(temp_elems, (*k0)[i])
temp_elems = append(temp_elems, (*k1)[j])

if (*k0)[i] < (*k1)[j] {
out = append(out, (*k0)[i])
i = i + 1
} else if (*k0)[i] > (*k1)[j] {
out = append(out, (*k1)[j])
j = j + 1
} else {
out = append(out, (*k0)[i], (*k1)[j])
i = i + 1
j = j + 1
}

if i == (len(*k0)) {
out = append(out, (*k1)[j:]...)
break
} else if j == (len(*k1)) {
out = append(out, (*k0)[i:]...)
break
}
l = (l - 1)
}

return out
}

0 comments on commit 06e60bb

Please sign in to comment.