Algorithms Flashcards
1
Q
Binary Search
Overview
A
An Algorithm that looks up a target in a sorted list. it returns the index of the target within the array. It cuts the searchable area in half on each iteration
2
Q
Binary Search
Pros and Cons
A
In it’s worst case, it outperforms linear search by cutting the searchable area in half on each iteration (binary logarithm [Ologn] where n is number of inputs)
So, as the input doubles, we only perform one more operation to find the target
3
Q
Binary Search
Big O
A
Big Ologn
n is the number of inputs. log is base 2 (Binary logarithm)
4
Q
Binary Search
What problems can this solve
A
quickly finding targets in sorted arrays/lists
5
Q
Binary Search
Think it, Write it, Code it
- What does the method do
- What’s the BigO
- What are the params and return values
- What are the code steps
A
/** * Binary search * Ologn - binary logarithmic * @param {number} target lookup value * @param {Array} arr sorted array * @returns {number} the index of the target in the array. -1 if not found in array. */ function binarySearch(target, arr){ let high = arr.length; let low = 0; let mid = Math.floor((high + low)/2) if(arr[0] === target) return 0; while(low !== mid && high !== mid){ if(target > arr[mid]){ low = mid; }else if(target < arr[mid]){ high = mid; }else{ return mid } mid = Math.floor((high + low)/2) } return -1 }