算法——二分查找变形题

给一个已经排好序的数组,在任意位置打断点后交换前后两个子数组,以此作为输入,输出n在该数组中的位置

eg:

输入 arr=[7,8,9,10,1000,10003,40000,1,2,3,4,5,6] n=9

输出 2

public class test {
    public static int findnumber(int[] num,int n){
        int half=num.length/2;
        int low=0;
        int high=num.length-1;

     while(low<=high){ if(n==num[half]){ return half; } //5,10,4 if(num[low]<num[half]){ if(n>num[low]&&n<num[half]){ high=half; half=(low+half)/2; }else{ low=half; half=(half+high)/2; } } else if(num[half]<num[high]){ if(n>num[half]&&n<num[high]){ low=half; half=(half+high)/2; }else{ high=half; half=(half+low)/2; } } } return -1; } public static void main(String[] args) { int[] arr={7,8,9,10,1000,10003,40000,1,2,3,4,5,6}; int n=9; int index = findnumber(arr, n); System.out.println(index); } }

 

posted @ 2019-04-25 22:36  高圈圈  阅读(172)  评论(0编辑  收藏  举报