-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path704. Binary Search
64 lines (56 loc) · 2.32 KB
/
704. Binary Search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
// You must write an algorithm with O(log n) runtime complexity.
// O(log n) gets exponentially smaller after splitting in half. Continue to cut in half.
// Binary search is a divide and conquer algo each step halves the elements it searches through.
// Example 1:
// Input: nums = [-1,0,3,5,9,12], target = 9
// Output: 4
// Explanation: 9 exists in nums and its index is 4
// Example 2:
// Input: nums = [-1,0,3,5,9,12], target = 2
// Output: -1
// Explanation: 2 does not exist in nums so return -1
// Constraints:
// 1 <= nums.length <= 104
// -104 < nums[i], target < 104
// All the integers in nums are unique.
// nums is sorted in ascending order.
// ----------------------------------------------------------------
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
// return the index of the target in nums
// continue halving with a while loop
var search = function(nums, target) {
// The first step is to create variables for the min and
// max indicies. This helps us bucket the inner array we
// are searching through.
let min = 0;
let max = nums.length - 1;
// create a while that allows us to serach for the the item
// so long our min variable is less than or equal to our max
while (min <= max) {
// Create a midpoint in loop using the min and max to start
// our search. min + max / 2
let mid = Math.floor((min + max) / 2)
if (target == nums[mid]) {
return mid
}
// if the item does not equal our original midpoint, we need to
// determine which half of the array we should begin to check.
// If the item is less than our starting midpoint, we need to
// adjust our max to now focus on the first half of our array.
else if (target < nums[mid]) {
max = mid - 1;
}
// If the item is greater than our starting midpoint, we need to
// adjust our min to now focus on the second half of our array.
else {
min = mid + 1;
}
}
// If our target is not inside of our element, return the sentinal value
return -1;
};