Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created September 11, 2021 16:48
Show Gist options
  • Save mustafadalga/70709d1c7eede261d5e193e0a7025cea to your computer and use it in GitHub Desktop.
Save mustafadalga/70709d1c7eede261d5e193e0a7025cea to your computer and use it in GitHub Desktop.
Divide And Conquer Pattern:Given a sorted array of integers, write a function called search, that accepts a value and returns the index where the value passed to the function is located. If the value is not found, return -1
function search(array, val) {
let min = 0;
let max = array.length - 1;
while (min <= max) {
let middle = Math.floor((min + max) / 2);
let currentElement = array[middle];
if (array[middle] < val) {
min = middle + 1;
}
else if (array[middle] > val) {
max = middle - 1;
}
else {
return middle;
}
}
return -1;
}
search([1,2,3,4,5,6],4) // 3
search([1,2,3,4,5,6],6) // 5
search([1,2,3,4,5,6],11) // -1
// Time Complexity - Log(N) - Binary Search!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment