查找算法:就是从一批数据中找到满足指定条件的记录,又称检索。
1)顺序查找:从第一个到最后一个逐个查找。
2)折半查找:二分查找。首先先将数据进行排序,然后再折半查找。
- 折半查找
/**
* Created by malei on 2016/12/4.
*/
public class 折半查找 {
public static void main(String[] args){
int[] arr = {45,190,234};
Log.show(search(arr,190));
}
private static int search(int[] arr,int x) {
int length = arr.length;
int low = 0;
int mid;
int high = length-1;
while (low <= high){
mid=(low+high)/2;
if(arr[mid] == x){
return mid;
}else if(arr[mid] >x){
high = mid-1;
}else {
low = mid+1;
}
}
return -1;
}
}