# 聊一聊前端算法面试——二分查找

### 写在前面

1. 二分查找的时间复杂度怎么求❓
2. 二分查找的递归和非递归怎么实现❓
3. 数组中存在重复的数据，怎么找出元素最后一次出现的位置❓
4. 数组中存在重复的数据，怎么找出第一个大于等于目标值的元素位置❓

### 1.二分查找的时间复杂度怎么求❓

• 若目标值比中间值大，即目标值在mid与high之间，就修改low的值。再对比中间值。

• 若目标值比中间值小，即目标值在low与mid之间，就修改high的值。再对比中间值。

``````n * n/2 * n/4 * n/8 * n/2^k ·····

### 二分查找的递归和非递归怎么实现❓

#### 非递归版

``````function binary_search(arr, key) {
var low = 0, high = arr.length - 1;
while(low <= high){
var mid = parseInt(low + (high - low) / 2);
if(key === arr[mid]){
return  mid;
} else if (key > arr[mid]){
low = mid + 1;
} else if (key < arr[mid]){
high = mid -1;
} else {
return -1;
}
}
};
var arr = [5,13,19,21,37,56,64,75,80,88,92];
var result = binary_search(arr, 21);
console.log(result);

#### 递归版

``````function binary_search(arr,low, high, key) {
if (low > high){
return -1;
}
var mid = low + ((high - low) >> 1);
if(arr[mid] == key){
return mid;
}else if (arr[mid] > key){
high = mid - 1;
return binary_search(arr, low, high, key);
}else if (arr[mid] < key){
low = mid + 1;
return binary_search(arr, low, high, key);
}
};
var arr = [5,13,19,21,37,56,64,75,80,88,92];
var result = binary_search(arr,0, 11, 21);
console.log(result);

### 3.数组中存在重复的数据，怎么找出元素最后一次出现的位置❓

``````function binary_search(arr, key) {
var low = 0, high = arr.length - 1;
while (low <= high) {
var mid =  low + ((high - low) >> 1);
if (arr[mid] > key) {
high = mid - 1;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
if ((mid == arr.length - 1) || (arr[mid + 1] != key)) return mid;
else low = mid + 1;
}
}
return -1;
}
var arr = [5,13,19,21,21,37,56,64,75,80,88,92];
var result = binary_search(arr, 21);
console.log(result);

### 总结

``````示例： [5,13,19,21,21,21,37,56,64,75,80,88,92],找出第一个大于等于21的元素位置