/*
* 2024.1.19
* 代码基本思想是先排序再查找
*/
public class demo01 {
public static void main(String[] args) {
int[] ns= {2,4,5,1,9,6,8,7};
int target=5;
//查找target在目标数组的下标位置
System.out.println(search(ns,target));
}
//排序
private static void sort(int[] ns) {
//冒泡排序
for(int i=0,n=ns.length;i<n-1;i++) {
for(int k=0;k<n-1-i;k++) {
if(ns[k]>ns[k+1]) {
ns[k]=ns[k]^ns[k+1];
ns[k+1]=ns[k]^ns[k+1];
ns[k]=ns[k]^ns[k+1];
}
}
}
}
//二分查找
public static int search(int[] num,int target) {
//先排序(冒泡排序)
sort(num);
//再查找(二分查找)
int low=0;
int heigh=num.length-1;
while(low<=heigh) {
int mid=(low+heigh)>>1;
if(num[mid]==target) {
return mid;
}else if(num[mid]>target) {
low=mid+1;
}else if(num[mid]<target) {
heigh=mid-1;
}
}
return -1;
}
}