13.6.2 - Binary Search Algorithm
Enroll to start learning
You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
Interactive Audio Lesson
Listen to a student-teacher conversation explaining the topic in a relatable way.
Introduction to Binary Search
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Today, we are going to talk about the Binary Search algorithm. Can anyone tell me what a search algorithm does?
It finds an element in an array or list.
Exactly! The Binary Search is a particularly efficient searching algorithm that works on sorted arrays. Does anyone know why sorting the data is important?
Because Binary Search won't work correctly on unsorted data.
That's right! Binary Search relies on the sorted order to eliminate half of the array at each step.
So, how does it actually divide the array?
Great question! It selects the middle element and compares it with the target value. If they match, we're done. If not, it decides which half of the array to keep searching in, based on whether the target is less than or greater than the middle element.
Can you summarize the steps?
Sure! 1. Find the middle element. 2. Check if it's the target. 3. If not, redesign the search space based on the comparison.
Steps of Binary Search
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Now, let's go over the step-by-step process of executing a Binary Search. Can you list the first step?
Find the middle element of the array.
Exactly! After finding the middle element, what comes next?
Compare it to the target value.
Correct! If you find a match, the search is complete. If not, what will you do?
We'd decide whether to search the left half or the right half depending on whether the target is lower or higher than the middle element.
That's right! By eliminating half of the remaining elements, we significantly speed up the search. Can anyone tell me the time complexity of Binary Search?
It's O(log n)!
Excellent! This logarithmic time complexity is what makes Binary Search so powerful for large datasets.
Implementing Binary Search
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Let's look at how we can implement the Binary Search algorithm in code. What do you think the initial parameters for our function need to be?
I guess we need the array and the target value.
Correct! We also need to track the minimum and maximum index positions. What do we initialize those to?
We would initialize the left to 0 and right to the last index of the array.
Exactly! Now, how do we implement the loop to keep checking while there are elements to compare?
We could use a while-loop that continues as long as left is less than or equal to right.
Right again! Within that loop, we calculate the middle index and compare the middle element with the target. If it's all set, how do we handle a successful find?
We'd return the index of the middle element.
Perfect! And if the target is not found?
We should return -1!
Well done, everyone! Coding Binary Search encapsulates all our discussed steps.
Introduction & Overview
Read summaries of the section's main ideas at different levels of detail.
Quick Overview
Standard
Binary Search is a searching algorithm designed to efficiently find the position of a target value within a sorted array. By continuously splitting the array in half, it significantly reduces the number of comparisons needed compared to linear search methods.
Detailed
Overview
Binary Search is an efficient algorithm designed for quickly locating a target value in a sorted array. Unlike Linear Search, which examines each element sequentially, Binary Search operates by repeatedly dividing the search range in half, thus reducing the total number of comparisons needed.
Key Steps
- Find the Middle Element: Start by identifying the middle element of the array.
- Check for Match: Compare the middle element with the target value. If they match, the search is successful.
- Reduce the Search Space: If the target is less than the middle element, repeat the search on the left half of the array; if it’s greater, search the right half.
- Repeat: Continue this process until the target is found or the search space is exhausted.
- Not Found: If the value is not found, return -1 to indicate this.
Significance
The efficiency of Binary Search is denoted by a time complexity of O(log n), making it much more efficient than Linear Search (O(n)) for large datasets, provided that the dataset is sorted. Understanding Binary Search is crucial for developing efficient algorithms in real-world applications.
Youtube Videos
Audio Book
Dive deep into the subject with an immersive audiobook experience.
Overview of Binary Search
Chapter 1 of 3
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Binary Search is a more efficient searching algorithm that works on sorted arrays. It repeatedly divides the search interval in half.
Detailed Explanation
Binary Search is designed to quickly locate a target value in a sorted array by continually dividing the array in half until it finds the value or concludes that it isn't in the array. Unlike linear search, which checks every element one by one, binary search operates much faster – particularly as the size of the array increases.
Examples & Analogies
Imagine trying to find a word in a dictionary. Instead of starting from the first page and flipping through every word, you can start in the middle. If the word you're looking for comes before the middle word, you can immediately ignore the second half of the dictionary, effectively cutting down the number of pages you need to check.
Steps of Binary Search
Chapter 2 of 3
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Steps:
1. Find the middle element of the list.
2. If the middle element is equal to the target value, return its index.
3. If the target value is smaller, repeat the search in the left half; otherwise, search in the right half.
Detailed Explanation
The process of binary search can be broken down into three clear steps:
1. Identify the middle element of the current search range. If this element matches the target, you have found what you’re looking for.
2. If the middle element is less than the target, it means the target must be in the right half of the array, so you adjust your search interval accordingly.
3. Conversely, if the middle element is greater than the target, the target must be in the left half. You continue this process of halving the search space until the target is found or the search space is exhausted.
Examples & Analogies
Consider searching for a specific item in a sorted list of books in a library. You first look at the book in the middle section. If your book is categorized alphabetically and the middle book starts with 'M', and your target starts with 'A', you know to search the earlier half of the alphabet. You continue this process until you either find your book or confirm it's not in the library.
Implementation Example of Binary Search
Chapter 3 of 3
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Example:
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Target found
}
if (arr[mid] < target) {
left = mid + 1; // Search in right half
} else {
right = mid - 1; // Search in left half
}
}
return -1; // Target not found
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
int index = binarySearch(arr, target);
System.out.println("Element found at index: " + index); // Output: Element found at index: 2
}
}
Time Complexity: O(log n)
Detailed Explanation
In this Java implementation of Binary Search, we define a method binarySearch that takes a sorted array and a target value as its parameters. The method maintains two pointers, left and right, representing the current range of the array we are searching in. A while loop continues as long as left is less than or equal to right, calculating the midpoint at each iteration. Depending on the value at the midpoint, we adjust our search boundaries until we either locate the target or determine that it is not present in the array. The time complexity of this algorithm is O(log n), making it highly efficient for large datasets.
Examples & Analogies
Think of it as playing a game where you have to guess a number between 1 and 100, and you are allowed to ask if your guess is too high or too low. Each time you guess, based on the response, you cut the range of possible answers in half. This strategy helps you reach the correct answer much faster than guessing sequentially.
Key Concepts
-
Binary Search: An efficient algorithm that finds a target value in a sorted array by dividing the search space in half.
-
Time Complexity O(log n): Binary Search significantly reduces the time required to search in a large data set compared to Linear Search.
-
Sorted Array: The prerequisite for Binary Search, as it relies on the ordered arrangement of elements.
Examples & Applications
Example of Binary Search on a sorted array like [10, 20, 30, 40, 50] to find the index of 30, which results in an index of 2.
A practical implementation in code that demonstrates how the Binary Search algorithm checks each element.
Memory Aids
Interactive tools to help you remember key concepts
Rhymes
In a sorted array, the right we might sway, To find what we're after without delay.
Stories
Imagine you're searching for treasure in a library. The shelves are perfectly ordered, and you can quickly skip to the centre shelf to find your book, more efficiently than wandering around each row.
Memory Tools
Half, Check, Narrow, Repeat (HCNR) - Remember the steps: Halve the array, Check the middle, Narrow down, Repeat the process.
Acronyms
MCRT - Middle, Compare, Right half, Try again.
Flash Cards
Glossary
- Binary Search
An efficient algorithm for finding an item from a sorted list of items by repeatedly dividing the search interval in half.
- Time Complexity
An estimation of the time required to run an algorithm as a function of the length of the input.
- Sorted Array
An array where the elements are arranged in a predefined order (ascending or descending).
Reference links
Supplementary resources to enhance your learning experience.