0
0
DSA Typescriptprogramming~30 mins

Binary Search Iterative Approach in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Binary Search Iterative Approach
📖 Scenario: You have a sorted list of numbers representing book IDs in a library. You want to quickly find if a specific book ID exists in the list.
🎯 Goal: Build a program that uses the iterative binary search method to find a given book ID in the sorted list.
📋 What You'll Learn
Create a sorted array of book IDs
Set a target book ID to search for
Implement the iterative binary search function
Print the index of the target book ID if found, or -1 if not found
💡 Why This Matters
🌍 Real World
Binary search is used in many applications like searching in databases, finding words in dictionaries, or looking up records quickly.
💼 Career
Understanding binary search helps in software development roles where efficient searching and sorting are important, such as backend development, data engineering, and algorithm design.
Progress0 / 4 steps
1
Create the sorted array of book IDs
Create a variable called bookIDs and assign it the sorted array [101, 203, 305, 407, 509, 611, 713].
DSA Typescript
Hint

Use const to create the array and assign the exact numbers in sorted order.

2
Set the target book ID to search
Create a variable called target and set it to the number 407.
DSA Typescript
Hint

Use const to create the target variable with the exact value 407.

3
Implement the iterative binary search function
Write a function called binarySearch that takes parameters arr (array of numbers) and target (number). Use a while loop with variables left and right to find the target in arr iteratively. Return the index if found, otherwise return -1.
DSA Typescript
Hint

Use left and right to track the search range. Calculate mid inside the loop. Compare arr[mid] with target and adjust left or right accordingly.

4
Print the search result
Call the binarySearch function with bookIDs and target, and print the returned index using console.log.
DSA Typescript
Hint

Use console.log(binarySearch(bookIDs, target)) to print the index.