Search algorithms are known as one of the hot trends among software engineers for years. These algorithms have been discussed since the beginning of the computer era, and they are fundamental of computer science. In this article, I try to describe one of the most efficient and easiest search algorithms, _Binary Search, _and show how can we make our own version in less than 5 minutes.


Algorithm Complexity

Before I start describing the algorithm, it is necessary to be familiar with the Algorithm Complexity concept. Being fast and efficient probably is the main purpose of studying algorithms. Algorithm Complexity is a measure to describe how an algorithm is performed against different sets of inputs, as described by Carnegie Mellon UniversityAlgorithmic complexity is concerned about how fast or slow particular algorithm performs.

The complexity of an algorithm can be shown by different notations, but the most common one is _Big O, _which describes its performance against the worst possible inputs. In other words, if an algorithm faces the worst possible set of inputs, it would take no longer than _Big O _steps to accomplish. Since the performance depends on inputs, it is shown with **_O(n), _**where n is the input size.

Having said that, algorithms are categorized into different groups performance-wisely:

Image for post


What is Binary Search

Binary Search is one of the most efficient search implementations that works over a list of **sorted integers. **Ithas the complexity of **O(n log n) **which is awesome when it comes to large data sets, however, it works only if the data is sorted beforehand. Due to the nature of the algorithm, also, it works only on integer lists.

Recursive algorithms

Binary Search is implemented using a recursive approach, where the search function is called by itself. Writing recursive algorithms is not always easy, but it is not a scary task for sure. The only point that you need to keep in mind is about the _Base Case _that makes the algorithm stops at some point, otherwise, the function continues forever.

Image for post

Recursive algorithms


Code Time

Now, it is time to write your version of the Binary Search. Although in this article I use Go, you can get the idea and write it with your preferred language. Additionally, there are tons of implementations available on GitHub that you can benefit for your problems.

Let’s start by defining a function that accepts an input array, target number, and first and last indexes of the given array. It returns a boolean that indicates if the target number is found as well as the index of it. In case the number is not found, it returns false, -1

#time-complexity #big-o-notation #algorithms #go #binary-search #algorithms

Binary Search with Go
1.20 GEEK