Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. /**
  2. * Linear search is a very simple search algorithm.
  3. * In this type of search, a sequential search is made over all items one by one.
  4. * Every item is checked and if a match is found then that particular item is returned,
  5. * otherwise the search continues till the end of the data collection.
  6. * @param {*} arr : An array in which you want to search the value
  7. * @param {*} valueToSearch : value to be search in array
  8. */
  9.  
  10. function linearSearch(arr , valueToSearch){
  11. let arrLength = arr.length
  12. for(let i = 0; i < arrLength; i++){
  13. if(arr[i] === valueToSearch){
  14. return i;
  15. }
  16. }
  17. return -1
  18. }
  19.  
  20. /**
  21. * Binary search is a fast search algorithm with run-time complexity of Ο(log n).
  22. * This search algorithm works on the principle of divide and conquer.
  23. * For this algorithm to work properly, the data collection should be in the sorted form.
  24. * @param {*} arr An array in which you want to search the value
  25. * @param {*} valueToSearch value to be search in array
  26. */
  27. function binarySearch(arr, valueToSearch){
  28. let lowerLimit = 0;
  29. let upperLimit = arr.length
  30. let midIndex = parseInt(( lowerLimit + upperLimit ) / 2 )
  31.  
  32. while(true)
  33. {
  34.  
  35. if( lowerLimit > upperLimit)
  36. return -1
  37.  
  38. if( valueToSearch === arr[midIndex])
  39. return midIndex
  40.  
  41. if(arr[midIndex] < valueToSearch){
  42. lowerLimit = midIndex + 1
  43. }
  44. else{
  45. upperLimit = midIndex - 1
  46. }
  47. midIndex = parseInt(( lowerLimit + upperLimit ) / 2 )
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement