Sorted Search
Explore how to implement a sorted search function using JavaScript. Understand both linear and binary search methods, focusing on binary search for improved efficiency. Learn to leverage sorted data to optimize search algorithms, preparing you for technical interviews involving algorithmic challenges.
We'll cover the following...
We'll cover the following...
Sorted Search
Instructions
Write a function that accepts a sorted array of integers and a number. Return the index of that number if present. The function should return -1 for target values not in the array.
Input: Array of Integers, Integer
Output: An integer from -1 onwards.
Examples:
search([1, 3, 6, 13, 17], 13); // -> 3
search([1, 3, 6, 13, 17], 12); // -> -1
Solution 1
This solution is very simple. We go through the array and try to find our target.
Time
Since we’re going through the whole array, the time complexity is:
O(n).
Space
Since we store a set number of variables, ...