Skip to content

Commit

Permalink
searching algo: binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
arnauddri committed Jan 25, 2015
1 parent ff208a6 commit 9eac56f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
23 changes: 23 additions & 0 deletions algorithms/searching/binary_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package bs

import ()

func search(sortedArray []int, el int) int {
init, end := 0, len(sortedArray)-1

for init <= end {
middle := ((end - init) >> 1) + init

if sortedArray[middle] == el {
return middle
}

if sortedArray[middle] < el {
init = middle + 1
} else {
end = middle - 1
}
}

return -1
}
27 changes: 27 additions & 0 deletions algorithms/searching/binary_search_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package bs

import (
"fmt"
"testing"
)

func TestSearch(t *testing.T) {
sorted := make([]int, 10000)

for i := 0; i < 10000; i++ {
sorted[i] = 2 * i
}

for i := 0; i < 10000; i++ {
index := search(sorted, 2*i)

if index != i {
fmt.Println(index)
t.Error()
}
}

if search(sorted, 3) != -1 {
t.Error()
}
}

0 comments on commit 9eac56f

Please sign in to comment.