二分查找
给定有序数组和带查找的数值,查找指定数值在指定数组的下标,没找到返回-1
解答
==数组要是乱序,需要先排序才能使用二分查找==。
定义数组左右边界,和中间指针,mid = (left + right)/ 2,不知道循环次数,使用while,跳出条件是左右指针相遇了,即分成每份只有一个元素了。指定值大于数组中间的数,直接舍弃左边,小于就是舍弃右边,不断重复此过程,一旦发现恰好指定值等于数组中间的值,跳出循环返回下标。
==没有找到返回-1.==
源代码
package com.bilibili;
import javax.sound.midi.MidiChannel;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author WangYH
* @version 2021.1.3
* @date 2023/4/7 15:19
*/
public class Main {
public static void main(String[] args) {
int[] arr1 = new int[] {
2,1,0,4,5,8,6,9,7,3};
Arrays.sort(arr1);
System.out.println(Arrays.toString(arr1));
System.out.println(search(arr1, 4));
}
public static int search(int[] arr,int tar){
int left = 0,right = arr.length -1;
while (left <= right){
int mid = (left + right) / 2;
int tmp = arr[mid];
if (tmp < tar){
left = mid + 1;
}else if (tmp > tar){
right = mid - 1;
}else {
return mid;
}
}
return -1;
}
}
递归解法
==思想是一样的,实现起来代码更加简短,但是不便于理解,而且有爆栈的风险==
package com.bilibili;
/**
* @author WangYH
* @version 2021.1.3
* @date 2023/4/7 15:19
*/
public class Main {
public static void main(String[] args) {
int[] arr = new int[]{
0,1,2,3,4,5,6,7,8,9};
int tar = 10;
System.out.println(binarySearch(arr, 0, arr.length -1, tar));
}
private static int binarySearch(int[] arr,int left,int right,int tar){
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
if (arr[mid] > tar){
return binarySearch(arr,left,mid - 1,tar);
}
else if (arr[mid] < tar){
return binarySearch(arr, mid + 1, right, tar);
}
else {
return mid;
}
}
}