java给定一个有序整型数组, 实现二分查找
程序员文章站
2024-03-17 14:43:04
...
public static int findKey(int[] array,int key) {
int left = 0;
int right = array.length-1;
int mid = (left + right)/2;
while(left <= right) {
mid = (left + right)/2;
if (key > array[mid]) {
left = mid + 1;
}
else if(key < array[mid]) {
right = mid - 1;
}
else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int [] arr = new int[] {1,2,3,4,5,6};
int key = 5;
int ret = findKey(arr,key);
System.out.println(ret);
//给定一个有序整型数组, 实现二分查找
}
}
上一篇: 牛客网机试题:全排列
下一篇: 二分法查找顺序数组(C语言实现)