java实现二分查找(折半查找)
算法思想:要求待查找的序列有序。每次取中间位置的值与待查关键字比较,如果中间位置的值比待查关键字大,则在前半部分循环这个查找的过程,如果中间位置的值比待查关键字小,则在后半部分循环这个查找的过程。直到查找到了为止,否则序列中没有待查的关键字。
代码示例:
public class BinarySearch {
public static int bisearch(int arr[], int target) {
int min = 0;
int max = arr.length - 1;
int mid;
while (min <= max) {
mid = (min + max) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
max = mid - 1;
} else {
min = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = new int[] { 1, 3, 6, 7, 11, 20, 39 };
System.out.println(bisearch(arr, 39));
}
}
还没有评论,来说两句吧...