Binary Search is an algorithm that allows you to quickly search through an array for a target item. Implementing it can also be a fairly common whiteboarding question when you're going through the interview process.
Why Would I Use This?
If you haven't worked with large arrays, you may wonder why you'd even want to learn this. Computers are so fast these days that searching through an array of 10, 20....100 items can take no time at all. However, what happens when your array consists of 2 million items? Searching for a particular target could take awhile.
This is where an algorithm like Binary Search comes in.
What Is Binary Search?
Binary Search allows you to quickly search through an array by cutting your search interval in half.
You will typically start in the middle of the array and check whether or not your target item is less than, greater than, or equal to the middle index. If it's smaller than the middle index, then you know that you'll only need to search the left half of the array. If it's greater than the middle index, then you know that you'll only need to search the right side of the array.
The algorithm keeps repeating this process until the middle index is equal to your target item. If your target item isn't present, then you could easily have the function return a -1 or false to indicate that what you're searching for isn't in the array.
Binary Search is a great algorithm to learn, especially when you're dealing with large amounts of data. It can quickly improve the time complexity of your applications from O(n) to O(Log n).
Thank you for taking the time to read this and I hope it was helpful.