Created
March 25, 2017 09:43
-
-
Save niteshpsit1/889b660840b858034447e1b0a102b7de to your computer and use it in GitHub Desktop.
Searching programs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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