0
0
DSA Javascriptprogramming~30 mins

Binary Search Iterative Approach in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Binary Search Iterative Approach
📖 Scenario: You have a sorted list of book IDs in a library system. You want to quickly find if a specific book ID exists in the list using a fast search method.
🎯 Goal: Build a program that uses the iterative binary search method to find a target book ID in a sorted array of book IDs.
📋 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 an iterative binary search function called binarySearch that takes arr and target as parameters
Use a while loop with variables left and right to search for targetID in bookIDs
Print the index of targetID if found, or -1 if not found
💡 Why This Matters
🌍 Real World
Binary search is used in many software systems to quickly find data in sorted lists, such as searching for a book in a library database or a contact in a phone book.
💼 Career
Understanding binary search is important for software developers and engineers because it teaches efficient searching techniques and algorithmic thinking, which are often tested in technical interviews.
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 to declare the array and include all numbers in order.

2
Set the target book ID to search
Create a variable called targetID and set it to 407
DSA Javascript
Hint

Use const to declare targetID and assign the number 407.

3
Write the iterative binary search function
Write a function called binarySearch that takes parameters arr and target. Inside it, create variables left set to 0 and right set to arr.length - 1. Use a while loop with the condition left <= right. Inside the loop, calculate mid as the floor of (left + right) / 2. If arr[mid] equals target, return mid. If arr[mid] is less than target, set left to mid + 1. Otherwise, set right to mid - 1. After the loop, return -1.
DSA Javascript
Hint

Follow the binary search steps carefully inside the while loop.

4
Print the search result
Call the binarySearch function with bookIDs and targetID as arguments. Print the returned index using console.log.
DSA Javascript
Hint

Use console.log(binarySearch(bookIDs, targetID)) to print the result.