Skip to content

Commit

Permalink
Tweak code example in binary-search approach
Browse files Browse the repository at this point in the history
The switch statement in the loop-with-switch approach had
two explicit cases and a default.

The three cases that exist are:
- equal
- less than
- greater than

If we want to have two explicit cases and a default, then it would
feel more symmetrical to have the less-than and greater-than cases
be defined explicitly with the equal case being the default.

However, it's hard to argue that any of the three are actually a
default here.

Instead I've changed it to have three explicit cases.
  • Loading branch information
kytrinyx committed Sep 30, 2023
1 parent b7051c2 commit d6b1e6b
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ package binarysearch
func SearchInts(list []int, key int) int {
for left, right := 0, len(list); left != right; {
mid := (left + right) / 2

switch {
case list[mid] == key:
return mid
case key < list[mid]:
right = mid
default:
case key > list[mid]:
left = mid + 1
}
}
Expand All @@ -37,7 +37,7 @@ A [`switch` with no condition][switch-no-condition] is used to check the value o
- If the value being searched for is less than the element at the index of the middle value, then `right` is set to the middle value
so that the next iteration will look at lower numbers.

- Otherwise, the value being searched for must be greater than the element at the index of the middle value, so `left` is set to the middle value
- Otherwise, the value being searched is greater than the element at the index of the middle value, so `left` is set to the middle value
plus one so that the next iteration will look for higher numbers.

If `left` and `right` are changed during the iterations so that they equal other, then the value being searched for is not in the slice of `int`s.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ case list[mid] == key:
return mid
case key < list[mid]:
right = mid
default:
case key > list[mid]:
left = mid + 1
}

0 comments on commit d6b1e6b

Please sign in to comment.