What is Binary Search?
Are you planning to use the Divide and Conquer Approach when you are dealing with elements? If you answer yes, then you know that Binary Search is probably the best searching technique that you can work on. This can be used to search for different elements in a sorted array.
Understanding Binary Search
There are so many types of searches that can be done. Why is binary search the choice of some people? They usually choose this because it can be done quicker as compared to a serial search. For serial search, you would need to have data that will be searched in halves for every step. This can be avoided when you use binary search.
This is also the choice of people who would need to go through a large amount of data within a limited time. This is faster as compared to other types of algorithms. There is one limitation that you should know though: the array or the list should be sorted first so that the binary search algorithm will work on it. This may take up just a little bit of your time to do. It will be worth it considering the amount of data that you can search after.
It is important that you get to understand how binary search works in a step-by-step process. Let us say that you have a sample array and there is an element that you are looking for.
- There are three variables that you have to consider at all times. These are startIndex, middleIndex, and endIndex.
- Take note that startIndex will always have the value of 0.
- endIndex can be calculated using the array length.
- The middleIndex can be gathered when you use the startIndex and the endIndex. You will divide the sum by 2. There are instances when this will be hard especially if you have come up with an odd number.
- You should have a While Loop available. This is where the variables will be placed.
- The While Loop will repeat the process until it finally ends.
- Remember that since you are going to use the startIndex and the endIndex to get the middleIndex, you can refer to the array that you have for all the details.
- Consider if the value that you will get is greater or less than the middleIndex.
- The moment that you find the value that is the same as your middleIndex, it is the number that you are searching for.
- Once you have done the process, then you have already completed the binary search.
You have hopefully learned enough data to know how to use binary search for your large data. Consider all of the things that are mentioned in this article so that you can use binary search to your advantage every time.