二分查找vc线性查找

public static int binarySearch(int[] args ,int key ){
           
           int upNum = args.length -1;
           int lowNum =0;
           int mid = lowNum +(upNum-lowNum)/2;
/**int mid =(low + high) 
             * 2;在一般情况下, 这个语句是不会出错的, 但是, 当low+high的值超过了
             * 最大的正int值 (231 - 1) 的时候, mid会变成负值,  这个时候, 会抛出
             * ArrayIndexOutOfBoundsException 异常..
             */
           int midValue =args[mid];
           if(midValue >key){
                 upNum =mid -1;
           }else if(midValue < key){
                 lowNum = mid +1;
           }else{
              return key;
           }
           return -(low+1);//找不到
}
  /**
     * 线性查找
     * 从args中查找key;返回查找到的次数
     * foreach
     */
    public int linearSearch(int[] args, int key) {
        long beginTime = System.currentTimeMillis();
        System.out.println(beginTime);
        System.out.println(System.currentTimeMillis());
        int m = -1;
        for (int n : args) {
            System.out.println("--------------");
            System.out.println(n + "***");
            if (n == key) {
                System.out.println("--------------");
                System.out.println("找到");
                long endTime = System.currentTimeMillis();
                System.out.println(endTime);
                System.out.println(endTime - beginTime);
                return m = n;
            } else {
                continue;
            }
        }
        return m;
    }
    static int sequenceSearching(int[] arr, int len, int key) {
        int i;
        for (i = 0; i < len && arr[i] != key; i++);
        if (i < len) {// 找到了,因为arr[i]==key
            System.out.println(i);
            return i;
        } else {//没找到
            return -1;
        }
    //return (i<len)?(i):(-1);
    }
 

 

你可能感兴趣的:(vc++)