📖 Scenario: You have a sorted list of numbers representing book IDs in a library. You want to find if a specific book ID is available using a fast method.
🎯 Goal: Build a recursive binary search function in JavaScript that checks if a given book ID exists in the sorted list.
📋 What You'll Learn
Create a sorted array called bookIDs with the exact values: [101, 203, 305, 407, 509, 611, 713]
Create a variable called targetID and set it to 407
Write a recursive function called binarySearch that takes arr, target, start, and end as parameters
Use recursion to find if targetID is in bookIDs
Print true if found, otherwise false
💡 Why This Matters
🌍 Real World
Binary search is used in many applications like searching in databases, looking up words in dictionaries, or finding items in sorted lists quickly.
💼 Career
Understanding binary search helps in software development roles that require efficient data searching and algorithm optimization.
Progress0 / 4 steps
1
Create the sorted array of book IDs
Create a sorted array called bookIDs with these exact values: [101, 203, 305, 407, 509, 611, 713]
DSA Javascript
Hint
Use const bookIDs = [101, 203, 305, 407, 509, 611, 713]; to create the array.
2
Set the target book ID to search
Create a variable called targetID and set it to 407
DSA Javascript
Hint
Use const targetID = 407; to store the book ID you want to find.
3
Write the recursive binary search function
Write a recursive function called binarySearch that takes parameters arr, target, start, and end. It should return true if target is found in arr, otherwise false. Use recursion to check the middle element and search the left or right half accordingly.
DSA Javascript
Hint
Use the middle index to compare and call binarySearch recursively on the left or right half.
4
Print the result of searching for the target ID
Use console.log to print the result of calling binarySearch with bookIDs, targetID, 0 as start, and bookIDs.length - 1 as end.
DSA Javascript
Hint
Call binarySearch(bookIDs, targetID, 0, bookIDs.length - 1) and print the result.
Practice
(1/5)
1. What is the main idea behind the binary search recursive approach when searching for a value in a sorted array?
easy
A. Divide the array into halves and search recursively in the half where the value can be.
B. Check every element one by one from start to end.
C. Sort the array first and then search linearly.
D. Use a loop to check elements until the value is found.
Solution
Step 1: Understand binary search logic
Binary search works by dividing the sorted array into two halves and deciding which half to search next based on comparison.
Step 2: Recognize recursive approach
In recursion, the function calls itself on the half where the target value may exist, reducing the search space each time.
Final Answer:
Divide the array into halves and search recursively in the half where the value can be. -> Option A