Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Last active June 20, 2018 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsphkhan/0a092b8e828d676ac1e70e20218522a0 to your computer and use it in GitHub Desktop.
Save jsphkhan/0a092b8e828d676ac1e70e20218522a0 to your computer and use it in GitHub Desktop.
Search using JavaScript
//Binary Search
//Runtime - O(log n)
//Faster than Linear search
function binarySearch(arr, num) {
//sort the array
//arr.sort() modifies the original array
arr.sort(function(a, b) {
return a - b;
});
var lowLimit = 0,
upLimit = arr.length - 1,
middle = 0;
while(lowLimit <= upLimit) {
middle = Math.floor((lowLimit + upLimit)/2);
//console.log(middle);
if(num === arr[middle]) {
return middle; //match found, return
} else if(num > arr[middle]) {
lowLimit = middle + 1; //right half
} else {
upLimit = middle - 1; //left half
}
}
return -1; //no match
}
//Linear Search
//Worst Case Runtime - O(n)
//Slower than Binary search
function linearSearch(arr, num) {
for(var i=0; i<arr.length; i++) {
if(num === arr[i]) {
return i; //match found, return the index
}
}
return -1; //not found
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment