Skip to content

Instantly share code, notes, and snippets.

@niteshpsit1
Created March 25, 2017 09:43
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 niteshpsit1/889b660840b858034447e1b0a102b7de to your computer and use it in GitHub Desktop.
Save niteshpsit1/889b660840b858034447e1b0a102b7de to your computer and use it in GitHub Desktop.
Searching programs
/**
* Linear search is a very simple search algorithm.
* In this type of search, a sequential search is made over all items one by one.
* Every item is checked and if a match is found then that particular item is returned,
* otherwise the search continues till the end of the data collection.
* @param {*} arr : An array in which you want to search the value
* @param {*} valueToSearch : value to be search in array
*/
function linearSearch(arr , valueToSearch){
let arrLength = arr.length
for(let i = 0; i < arrLength; i++){
if(arr[i] === valueToSearch){
return i;
}
}
return -1
}
/**
* Binary search is a fast search algorithm with run-time complexity of Ο(log n).
* This search algorithm works on the principle of divide and conquer.
* For this algorithm to work properly, the data collection should be in the sorted form.
* @param {*} arr An array in which you want to search the value
* @param {*} valueToSearch value to be search in array
*/
function binarySearch(arr, valueToSearch){
let lowerLimit = 0;
let upperLimit = arr.length
let midIndex = parseInt(( lowerLimit + upperLimit ) / 2 )
while(true)
{
if( lowerLimit > upperLimit)
return -1
if( valueToSearch === arr[midIndex])
return midIndex
if(arr[midIndex] < valueToSearch){
lowerLimit = midIndex + 1
}
else{
upperLimit = midIndex - 1
}
midIndex = parseInt(( lowerLimit + upperLimit ) / 2 )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment