You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
854 B

6 years ago
  1. package storage
  2. import "testing"
  3. func TestBinarySearch(t *testing.T) {
  4. var testInput []int
  5. testInput = []int{-1, 0, 3, 5, 9, 12}
  6. if 3 != binarySearchForLargerThanTarget(testInput, 4) {
  7. t.Errorf("failed to find target %d", 4)
  8. }
  9. if 3 != binarySearchForLargerThanTarget(testInput, 3) {
  10. t.Errorf("failed to find target %d", 3)
  11. }
  12. if 6 != binarySearchForLargerThanTarget(testInput, 12) {
  13. t.Errorf("failed to find target %d", 12)
  14. }
  15. if 1 != binarySearchForLargerThanTarget(testInput, -1) {
  16. t.Errorf("failed to find target %d", -1)
  17. }
  18. if 0 != binarySearchForLargerThanTarget(testInput, -2) {
  19. t.Errorf("failed to find target %d", -2)
  20. }
  21. }
  22. func binarySearchForLargerThanTarget(nums []int, target int) int {
  23. l := 0
  24. h := len(nums)
  25. for l < h {
  26. m := (l + h) / 2
  27. if nums[m] <= target {
  28. l = m + 1
  29. } else {
  30. h = m
  31. }
  32. }
  33. return l
  34. }