JavaScript Interview Coding Test Problem 3
Published: 2022-07-09 10:57:55

**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.

**Sorted Search**
**Instructions**
Write a function that accepts a sorted array of integers and a numher. Return the index of that number if present. The functiDn should return -i for target values not in the array.
Input: Array of Integers, Integer

Output: An integer from -i onwards.
**Examples**
search([1, 3, 6, 13, 17], 13); // -> 3
search([l, 3, 6, 13, 17], 12); // -> -1

```
1	function search(numbers, target) {
2	// Your code here 3	}
```
**Solution 1**

```
1	function search(numbers, target) {
2	for(let i = 0; i < numbers.length; i++) {
3		if(numbers[i] === target) {
4		  return i;	
5		}
6	}	
7			
8	return -1; 
```
This solution is very simple. We go through the array and try to find Dur 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, space complexity is:
O(1)
**Binary Search**
We can cDme up with a better solution. Since the array is sDrted, we can essentially jump around the array until we find the index we’re looking for.
**Finding a Word**
Imagine looking for a word in a dictionary. Would it be efficient to go  through every single word until we find the one we want? No, that would be horribly inefficient.
A better approach would be to Dpen the dictiDnary halfway. If our word is alphabetically before the words in the middle page, we know our word is in the first half of the hoDk.
We can then flip to -1/4 of the way through the dictionary. Again, repeating the above process, we can eliminate another half of the remaining pages.
We can repeat the above steps again and again until we find our word. This ensures  that even if the dictionary is huge, we can find  Dur word much faster than if we were to go through each word individually.
**Scaling**
In fact, if we double the size of the dictionary by adding in more words, we would only have to repeat this process one more time. That’s not much more work even thDugh the dictionary is much thicker.
Let’s turn this approach into code.
**Solution 2**

```
function binarySearch(numbers, target) (
let startIndex = 0;
let endIndex = numbers.length - 1;
if(target ‹ numbers[startlndex] || target > numbers[endIndex]){
  return--1;
}
while(true) {
  if(numbers[startlndex] === target) {
    return tartIndex;
  }
14	if(numbers[endIndex].===-target).{
15	return.endlndex;
16	........}
17
18	.- ......if(endIndex. -.startIndex. ‹=-1).{
19	//-indicates-the-number-isn't-present
20	return.-1;
21	........}
22
23	 
      const middleIndex = Math.floor((startIndex + endIndex) / 2);
24
25	if(target › numbers[middleIndex]) (
26	 startIndex = middleIndex + 1;
27	} else if(target ‹ numbers[middlelndex]) { 
          endIndex = middleIndex - 1;
	} else {
	return middleIndex;
  }

}
```
**How it Works**
We start by ensuring that the target is within range of the array, returning
false Otherwise.

In the loop, we first check if the target is equal to the values at the beginning and end of Dur array. Then we check if the target is larger  Dr smaller than  the value at the center.
If it’s smaller than the value at the center, we know that it’s going to be somewhere in the 1st half of the array. We can focus on that.
If it’s larger, we know that it can’t possibly be in the first half, so we can focus on searching the 2nd half.
Over and over, we cut the amount we have to search by half until we close in on its locatiDn. If we find it alDng the way, we can stDp and return its index.
**Time**
We’re eliminating half of the array in every iteration of our loop, so time
complexity is O(log2(n)), which simplifies to:
O(log(n))
**Space**
The space complexity is again:
O(1)
**Conclusion**
Dealing with sDrted data allows us to make many optimizations. We knDw the relationship of an item to the items before it and after it, allowing us to jump around the data and hone in on the value we’re looking for.
If data comes in  unsorted, sometimes it would  be wise to sort it  ourselves.  If we have a sDlution with o(n^2) time cDmplexity, it’s worth it to see if we can sortthedaTa.
Sorting it would be an o(n  *  log(n) )  process,  which  is  better than  o(n•2)  . Once it’s sorted, the next steps are often linear  or logarithmic,  meaning  they are insignificant compared to the sorting itself.