Sorted Search
Learn two different ways to complete the search of a sorted array. We'll go over the brute force method and a more elegant method.
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
Press + to interact
function search(numbers, target) {// Your code here}
Solution 1
Press + to interact
function search(numbers, target) {for(let i = 0; i < numbers.length; i++) {if(numbers[i] === target) {return i;}}return -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 ...