Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 )
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement