What if you could find anything in a huge list in just a few steps instead of searching forever?
Why Binary Search and What Sorted Order Gives You in DSA C++ - The Real Reason
Imagine you have a huge phone book with thousands of names, and you want to find one person's phone number. You start at the first page and look at every name one by one until you find the right one.
This way is very slow and tiring because you might have to check many names before finding the one you want. If the book is very big, it can take a long time and you might make mistakes by skipping or repeating pages.
Binary Search uses the fact that the phone book is sorted alphabetically. Instead of checking every name, you open the book in the middle, see if the name is before or after, and then only look in that half. You keep cutting the search area in half until you find the name quickly and easily.
int findIndex(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) return i;
}
return -1;
}int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}It lets you find items in huge sorted lists very fast, saving time and effort.
When you search for a word in a dictionary app, it uses binary search behind the scenes to quickly jump to the right page instead of flipping through every word.
Searching one by one is slow for big lists.
Sorted order lets us cut the search area in half each time.
Binary Search finds items quickly by using sorted order.