java基础之二分查找,可变参运用

一、

public class BinarySeachTest {
public static void main(String[] args) {
    int[] arr = new int[]{22,54,88,97,105,112};
    System.out.println(binarySeach(arr, 112));
}
/**
 *
 * @return 返回传入的value在数组位置
 */
public static int binarySeach(int[] num,int value){
    int start=0;  //数组的开始下标
    int end =num.length-1;  //数组的结尾下标
    while(start<=end){
        int middle = (start+end)/2;  //中间位置
        if(num[middle]>value){
            end=middle-1;
        }else if(num[middle]<value){
            start=middle+1;
        }else {
            return middle;
        }
    }
    return -1;
}

}

二、可变参:定义一个方法需要接受多个参数,并且多个参数类型一致

  格式:
        修饰符 返回值类型 方法名(参数类型... 形参名){  }
              等价与
        修饰符 返回值类型 方法名(参数类型[] 形参名){  }

  例子:
        public class VariableParameter {
             public static void main(String[] args) {
                int[] arr = {4,5,9,10};
                System.out.println(getSum1(arr));
                System.out.println(getSum2(arr));
            }

            public static int getSum1(int[] num){
                int sum = 0;
                for (int i : num) {
                    sum+=i;
                }
                return sum;
            }
            public static int getSum2(int...num){
                int sum = 0;
                for (int i : num) {
                    sum+=i;
                }
                return sum;
              }
            }
posted @ 2020-08-11 00:08  jock_javaEE  阅读(65)  评论(0编辑  收藏  举报