Skip to content

Instantly share code, notes, and snippets.

@fortunee
Last active February 18, 2019 22:45
Show Gist options
  • Save fortunee/9492ce638e22242e55c0d3b1dda39b31 to your computer and use it in GitHub Desktop.
Save fortunee/9492ce638e22242e55c0d3b1dda39b31 to your computer and use it in GitHub Desktop.
searchAlgorithms
const binarySearch = (array, value) => {
/**
* 1. Define a midPoint variable
* 2. Define and initialize min and max index variables
* 3. Perform a loop through the array
* 4. Assign the mid index of the array to the midPoint variable
* 5. Compare the current midPoint value with search value
* 6. Return value if midPoint value === search value
* 7. Reassign the min index if the midPoint val < search val
* 8. Reassign the max index if the midPoint val > search val
* 9. Return -1 if search val !found
*/
let midPoint,
min = 0,
max = array.length - 1;
while (min <= max) {
midPoint = Math.floor((min + max) / 2);
if (array[midPoint] === value) {
return array[midPoint];
} else if (array[midPoint] < value) {
min = midPoint + 1;
} else {
max = midPoint - 1;
}
}
return -1;
}
binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9], 20); // -1
binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9], 4); // 4
const linearSearch = (list, searchItem) => {
for(let i = 0; i < list.length; i++) {
if(list[i] === searchItem) {
return list.indexOf(searchItem);
}
return -1;
}
};
const arr = ['a', 'd', 'k', 'b', 'e', 'i', 'm']
linearSearch(arr, 'e');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment