Explaining Binary Search in a Simple Way

Today I try to explain binary search in a simple way. Binary search is a search algorithm that finds the position of a target value within a sorted array. Sorted array is an important point here.

To explain binary search, we need a array to exemplify.

arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

In this array, we have 10 elements, from 1 to 10. Binary search works by comparing the target value to the middle element of the array.

For example, if we want to find the number 5 in the array, we start by comparing 5 to the middle element of the array, which is 6.

Next step is to compare 5 to 6. If 5 is less than 6, we can discard the right half of the array. The new array is now:

arr := []int{1, 2, 3, 4, 5}

Now we repeat the process, comparing 5 to the middle element of the new array, which is 3.

Next step is to compare 5 to 3. If 5 is greater than 3, we can discard the left half of the array. The new array is now:

arr := []int{4, 5}

Now we repeat the process, comparing 5 to the middle element of the new array, which is 5. And we found the number 5 in the array.

In this simple example we found the number 5 in 3 steps. This is my simple explanation of binary search.

Now I can implement the binary search algorithm in Go.

package main

func search(arr []int, searchItem int) int {
	minus := 0
	max := len(arr) - 1

	for minus <= max {
		middle := (minus + max) / 2
		tryFind := arr[middle]
		if tryFind == searchItem {
			return middle
		}
		if tryFind > searchItem {
			max = middle - 1
		} else {
			minus = middle + 1
		}
	}

	return -1
}

Now I can use the search function to find the number 5 in the array.

func main() {
	arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	searchItem := 80
	pos := search(arr, searchItem)
	var message string
	message = fmt.Sprintf("Find item %d in %d position", searchItem, searchItem)
	if pos == -1 {
		message = fmt.Sprintf("Item %d not found", searchItem)
	}
	fmt.Println(message)
}

This is the output of the program:

Item 80 not found

This algorithm reminds me of a phrase I often hear: ‘divide and conquer! I hope this post, along with the others, helps you in your studies and, more importantly, helps you understand that the best path is always through deep knowledge!

See you next time! Thanks for reading my blog. Hugs!