Last active
August 13, 2021 23:51
-
-
Save jose-camilo/1afe38db91dbd98e2350f7211d763790 to your computer and use it in GitHub Desktop.
2D Array Binary Search Golang
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 ( | |
"errors" | |
"fmt" | |
"os" | |
) | |
func main() { | |
array := [2][8]int{ | |
{17, 16, 15, 14, 13, 12, 11, 10}, | |
{9, 8, 7, 6, 5, 4, 3, 2}, | |
} | |
x, y, err := find(array, 2) | |
if err != nil { | |
fmt.Println(err.Error()) | |
os.Exit(0) | |
} | |
fmt.Printf("\ninput array: %+v", array) | |
fmt.Printf("\nfound value %d in position: %d,%d", array[x][y], x, y) | |
} | |
// find recieves a 2x8 array and a key integer to search. | |
func find(array [2][8]int, key int) (x int, y int, err error) { | |
columnLength := len(array[0]) | |
low := 0 | |
high := columnLength - 1 | |
// As we only have two rows, we can figure out in | |
// which row the number is positioned in O(1). | |
if key < array[x][columnLength-1] { | |
x++ | |
} | |
// Then we do the binary search in only one row | |
// in O(Log(n)). | |
for low <= high { | |
// In golang `/` on an int works the same way as `//` | |
// in python. | |
y = (low + high) / 2 | |
if array[x][y] == key { | |
return x, y, nil | |
} else if array[x][y] > key { | |
low = y + 1 | |
} else { | |
high = y - 1 | |
} | |
} | |
return 0, 0, errors.New("the number doesn't exist") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment