Repository navigation
Searching Algorithm
How do we search?
Given an array, the simplest way to search for a value is to look at every element in the array and check if it's the value we want.
if our array is not sorted, in this case the best way to search is to look at every element in the array. => That is called Linear Search
JavaScript has search!
There are many different search methods arrays in JavaScript:
- indexOf
- includes
- find
- findIndex
Best => O(1)
Worst => O(n)
Average => O(n)
Binary Search is a much faster from a search
Rather than eliminating one element at a time, you can eliminate half of the remaining elements at a time
Binary Search only works on sorted arrays => so the data has to be sorted to seach using Binary search
The idea is Divide and Conquer
Binary Search Pseuducode
- This function accepts a sorted array and a value
- Create a left pointer at the start of the array, and a right pointer at the end of the array
- While the left pointer comes before the right pointer:
- Create a pointer in the middle
- if you find the value you want, return the index
- if the value is too small, move the left pointer up
- if the value is too large, move the right pointer down
- If you never find the value return -1.
function binarySearch(arr, value) {
let start = 0;
let end = arr.length -1;
let middle = Math.floor((start + end) / 2);
while (arr[middle] !== value && start <= end) {
if (value < arr[middle]) end = middle - 1;
else start = middle + 1;
middle = Math.floor((start + end) / 2);
}
return arr[middle] === value ? middle : -1;
}
binarySearch([2, 5, 6, 9, 13, 15, 28], 15)Worst and average case => O(log n)
Best case => O(1) Worst and Average case => O(log n)
search for substrings in a larger string.
Suppose you want to count the number of times a smaller string appears in a longer string.
for example I wanna search for haha in the string harold said haha in hamburg
-
- Loop over the longer string
-
- Loop over the shorter string
-
- If the characters don't match, break out the inner loop
-
- If the characters do match, keep going
-
- If you complete the inner loop and find a match, increment the count of matches
-
- Return the count
function naiveSearch(long, short) {
for(let i = 0; i < long.length; i++) {
for(let j = 0; j < short.length; j++) {
short[j] !== long[i+j]
}
}
}
naiveSearch("lorie loled", "lol")