specialCoder

正文：二分查找

二分查找法的基本实现

``````function bsearch(array,low,high,target)
{
if (low > high) return -1;
var mid = Math.floor((low + high)/2);
if (array[mid]> target){
return  bsearch(array, low, mid -1, target);
} else if (array[mid]< target){
return  bsearch(array, mid+1, high, target);
}ese{return mid;}

}
``````

``````function bsearchWithoutRecursion(array,low,high,target)
{
while(low <= high)
{
var mid = Math.floor((low + high)/2);
if (array[mid] > target){
high = mid - 1;
}else if (array[mid] < target){
low = mid + 1;
}else{
return mid;
}
}
return -1;
}

``````

用二分查找法找寻边界值

var array = {2, 3, 5, 7, 11, 13, 17};
var target = 7;

``````function BSearchUpperBound(array,low,high,target)
{
if(low > high || target >= array[high]) return -1;

var mid = (low + high) / 2;
while (high > low)
{
if (array[mid] > target){
high = mid;
} else{
low = mid + 1;
}
mid = (low + high) / 2;
}

return mid;
}
``````

``````function BSearchLowerBound(array,low,high,target)
{
if(high < low  || target <= array[low]) return -1;

var mid = (low + high + 1) / 2; //make mid lean to large side
while (low < high)
{
if (array[mid] < target){
low = mid;
}else{
high = mid - 1;
}
mid = (low + high + 1) / 2;
}

return mid;
}``````

target >= array[high]改为 target > array[high]

array[mid] > target改为array[mid] >= target

``````//return type: pair<int, int>
//the fisrt value indicate the begining of range,
//the second value indicate the end of range.
//If target is not find, (-1,-1) will be returned
pair<int, int> SearchRange(int A[], int n, int target)
{
pair<int, int> r(-1, -1);
if (n <= 0) return r;

int lower = BSearchLowerBound(A, 0, n-1, target);
lower = lower + 1; //move to next element

if(A[lower] == target)
r.first = lower;
else //target is not in the array
return r;

int upper = BSearchUpperBound(A, 0, n-1, target);
upper = upper < 0? (n-1):(upper - 1); //move to previous element

//since in previous search we had check whether the target is
//in the array or not, we do not need to check it here again
r.second = upper;

return r;
}
``````

Javascript 编程基础
javascript 基础知识 ，全面学习JS编程。

1.8k 声望
105 粉丝