首页 > 代码库 > javascript-binarySearch

javascript-binarySearch

前提: 数组已排序,且为正整数数组.

 1 function brnarySearch(arg, arr) { 2     var right = arr.length - 1; 3     var left = 0; 4     while(left <= right) { 5           var mid = left + parseInt( (right - left) / 2 ); 6           if(arg < arr[mid]) right = mid - 1; 7           else if(arg > arr[mid]) left = mid + 1; 8           else return mid; 9     }10     return -1;11 }12 var arr = [1, 3, 5, 7, 9, 11, 12, 44, 56];13 console.log(brnarySearch(9, arr));

 

javascript-binarySearch