# 二分查找(折半查找)

title: 二分查找
tags: 数据结构与算法之美
author: 辰砂

## 二、过程

若k==R[mid].key，查找成功



## 三、算法描述

### 1.非递归

int Search_Bin(SSTable ST,KeyType key){
//若找到，则函数值为该元素在表中的位置，否则为0
low=1;high=ST.length;						 while(low<=high){
mid=(low+high)/2;
if(key==ST.R[mid].key) return mid;
else if(key<ST.R[mid].key) high=mid-1;//前一子表查找
else low=mid+1;                       		//后一子表查找
}									    return 0;		//表中不存在待查元素
}


### 2.递归

int Search_Bin (SSTable ST, keyType key, int low, int high)
{
if(low>high) return 0;   //查找不到时返回0
mid=(low+high)/2;
if(key==ST.elem[mid].key)  return mid;
else if(key<ST.elem[mid].key)
return search_Bin(ST,key,low,mid-1);//递归
else  return search_Bin(ST,key,mid+1,high); //递归
}



### 3、完整代码

public class BinarySearch {

public static void main(String[] args) {

int[] nums = {1, 4, 5, 8, 9};
System.out.println(binarySearch(nums, 1));
System.out.println(binarySearchRecursion(nums, 1, 0, nums.length - 1));
}

/**
* 循环
*
* @param nums
* @param target
*
* @return
*/
public static int binarySearch(int[] nums, int target) {
if (nums.length < 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left - right) / 2 + right;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

/**
* 递归
*
* @param nums
* @param target
* @param left
* @param right
*
* @return
*/
public static int binarySearchRecursion(int[] nums, int target, int left, int right) {

if (nums.length < 0 || left < 0 || right > nums.length - 1) {
return -1;
}

int mid = (left - right) / 2 + right;
if (left <= right) {
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
return binarySearchRecursion(nums, target, mid + 1, right);
} else {
return binarySearchRecursion(nums, target, left, mid - 1);
}
}
return -1;
}


## 五、优化

mid=(low+high)/2;
if(key==ST.R[mid].key) return mid;
else if(key<ST.R[mid].key) high=mid-1;//前一子表查找
else low=mid+1;


int mid = (left - right) >> 2 + right;


## 六、二分法练习

https://leetcode.com/problemset/all/?topicSlugs=binary-search

https://www.cnblogs.com/ciyeer/p/9065781.html

posted @ 2018-11-09 11:23  辰砂tj  阅读(...)  评论(...编辑  收藏