zoukankan      html  css  js  c++  java
  • 算法——二分查找变形题

    给一个已经排好序的数组,在任意位置打断点后交换前后两个子数组,以此作为输入,输出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); } }
  • 相关阅读:
    工厂增强
    面试题
    SpringBean生命周期及作用域
    字符串
    带参数方法实例
    带参数方法
    人机猜拳
    类的无参方法
    类和对象实例2
    类和对象实例1
  • 原文地址:https://www.cnblogs.com/gaoquanquan/p/10771594.html
Copyright © 2011-2022 走看看