Commits

Anonymous committed f124b6a

added binary search

  • Participants
  • Parent commits ab8e167

Comments (0)

Files changed (3)

File searching/Makefile

 
 GOFILES=\
 	sequential_search.go\
-
+	binary_search.go\
 
 include $(GOROOT)/src/Make.pkg

File searching/binary_search.go

+/*
+
+*/
+package search
+
+
+func BinarySearch(array []int, t int) bool {
+	low := 0
+	high := len(array) - 1
+	for {
+		if low <= high {
+			ix := (low + high) / 2
+			if t == array[ix] {
+				return true
+			} else if t < array[ix] {
+				high = ix - 1
+			} else {
+				low = ix + 1
+			}
+			continue
+		}
+		break
+	}
+	return false
+}

File searching/search_test.go

 	if !s {
 		t.Fail()
 	}
+	s = SequentialSearch(array, 99)
+	if s {
+		t.Fail()
+	}
 }
 
-
+func TestBinarySearch(t *testing.T) {
+	array := []int{1, 4, 8, 9, 11, 15, 17, 22, 23, 26}
+	s := BinarySearch(array, 11)
+	if !s {
+		t.Fail()
+	}
+	s = BinarySearch(array, 99)
+	if s {
+		t.Fail()
+	}
+}