0
0
DSA Javascriptprogramming~30 mins

Binary Search vs Linear Search Real Cost Difference in DSA Javascript - Build Both Approaches

Choose your learning style9 modes available
Binary Search vs Linear Search Real Cost Difference
📖 Scenario: Imagine you have a list of product prices in a store. You want to find if a certain price exists in the list. You can look through the list one by one (linear search) or use a faster method if the list is sorted (binary search). This project will help you see the difference in how many steps each method takes.
🎯 Goal: You will create a list of prices, set a target price to find, write code to count steps taken by linear search and binary search, and then print the counts to compare their costs.
📋 What You'll Learn
Create an array called prices with these exact values: [5, 12, 19, 23, 38, 45, 56, 67, 72, 88]
Create a variable called targetPrice and set it to 38
Write a function called linearSearch that takes prices and targetPrice and returns the number of steps taken to find the target or the length of the array if not found
Write a function called binarySearch that takes prices and targetPrice and returns the number of steps taken to find the target or the number of steps taken to conclude it is not found
Print the number of steps taken by linearSearch and binarySearch for the targetPrice
💡 Why This Matters
🌍 Real World
Searching for items quickly in sorted lists like product prices, phone contacts, or dictionary words.
💼 Career
Understanding search algorithms helps in optimizing software performance and writing efficient code.
Progress0 / 4 steps
1
Create the price list
Create an array called prices with these exact values: [5, 12, 19, 23, 38, 45, 56, 67, 72, 88]
DSA Javascript
Hint

Use const prices = [...] to create the array with the exact numbers.

2
Set the target price
Create a variable called targetPrice and set it to 38
DSA Javascript
Hint

Use const targetPrice = 38; to set the price you want to find.

3
Write linear search function
Write a function called linearSearch that takes prices and targetPrice and returns the number of steps taken to find the target or the length of the array if not found. Use a for loop with variable i to check each price.
DSA Javascript
Hint

Use a for loop to check each price. Return i + 1 when found to count steps.

4
Write binary search function and print results
Write a function called binarySearch that takes prices and targetPrice and returns the number of steps taken to find the target or the number of steps taken to conclude it is not found. Use variables left, right, and steps. Then print the number of steps taken by linearSearch(prices, targetPrice) and binarySearch(prices, targetPrice).
DSA Javascript
Hint

Use a while loop with left and right pointers. Increase steps each loop. Print results with console.log.