Skip to content

Commit f78ae3e

Browse files
committed
Implemented a rough version of binary search a I wrote the article
1 parent fab53a2 commit f78ae3e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
var lookingFor int = 6
7+
var sortedList []int = []int{1, 3, 4, 6, 7, 9, 10, 11, 13}
8+
fmt.Println("Looking for", lookingFor, "in the sorted list:", sortedList)
9+
10+
index := binarySearch(sortedList, lookingFor)
11+
if index >= 0 {
12+
fmt.Println("Found the number", lookingFor, "at:", index)
13+
} else {
14+
fmt.Println("Didn't find the number", lookingFor, ":(")
15+
}
16+
}
17+
18+
func binarySearch(sortedList []int, lookingFor int) int {
19+
var lo int = 0
20+
var hi int = len(sortedList) - 1
21+
22+
for lo <= hi {
23+
var mid int = lo + (hi-lo)/2
24+
var midValue int = sortedList[mid]
25+
fmt.Println("Middle value is:", midValue)
26+
27+
if midValue == lookingFor {
28+
return mid
29+
} else if midValue > lookingFor {
30+
// We want to use the left half of our list
31+
hi = mid - 1
32+
} else {
33+
// We want to use the right half of our list
34+
lo = mid + 1
35+
}
36+
}
37+
38+
// If we get here we tried to look at an invalid sub-list
39+
// which means the number isn't in our list.
40+
return -1
41+
}

002_binary_search/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
See <http://www.calhoun.io/lets-learn-algorithms-an-intro-to-bubble-sort/> for the tutorials that go along with the code in `000_tutorial` and talk about the practice problems in `practice_problems`

0 commit comments

Comments
 (0)