In the previous material, we have learned about what binary search algorithms are. There also has been embedded a piece of material about the basic concepts and simple implementation of this algorithm.
On this occasion, we will continue the previous material by knowing how it works. By knowing the working concept of binary search, you will be able to easily create a program or source code based on data search with this algorithm.
You need to know, binary search algorithms can be implemented in all programming languages. Especially in programming languages that can manage data dynamically. Examples are the programming languages PHP, JavaScript, Java, C #, C ++, Python, etc.
How Binary Search Works
The workings of this algorithm are checking data repeatedly by removing half the amount of data until finding a match. With a concept like this, the scope of the search for data will get smaller every time you do the iteration process.
Keep in mind, the requirement in this search process is that data must be sorted first. If it isn't sorted, the search process will not be able to run perfectly.
Why does the data have to be sorted first in using the binary search algorithm?
Good a question.
In the binary search algorithm, three data points help the data search process. The point is at the beginning of the data (min), the middle of the data (mid), and the data at the end of the data (max).
The point that has the most important role is the midpoint (mid). This point serves as a point to match the search data, as a point to divide the data into two and as a point to check the position of the data.
The process of checking the position in question is to check the data you want to find by comparing it with the middle value. This process checks whether the position of the data sought is smaller than the middle value or vice versa. Then take half the data that meets the checking results and discard the rest.
This position checking process answers the question of why data must be sorted first. If not, this process can't be carried out.
Illustration of Binary Search
We have prepared illustrations of how binary search works in the form of animation in two different case studies.
Case Study 1
In this first case study, we will see an illustration of the search for number 2 from the sequence of numbers 1 2 3 4 5 6 7 8 9 10. The following is an illustration of finding the data.
Case Study 2
Previously, we have seen the process of binary search in sequential data series. In this case, we will see an illustration of searching M data in randomly arranged data. The data to be used is S 8 3 7 J K S 9 1 N H.
Do you understand how the binary search algorithm works?
Henceforth, we will implement a binary search by making the script with a programming language. For the languages we will use are PHP and JavaScript.