Binary search and time and space complexity

package com.wei.demo.Annotation;

/**
 * 二分查找算法Java:循环方法和递归方法
 * 思想:我们查找的数组范围是low(0)~high(len-1)。每次查找中间的元素,我们猜测的数字是guess=(low+high)/2;
 * 实际数字为item,如果猜测数字guess小于item,那范围变为:guess+1~high,low=guess+1位置开始;
 * 如果猜测数字guess大于item,那就范围变为low~guess-1
 * 数组:必须是有序的
 * 结果:返回想要数字的位置
 */
public class binary_search {

    public static void main(String[] args) {
        int[] array = {1, 2, 33, 55, 66, 88, 99, 567, 789, 999,1000,10001,100002};
       // index(array,item);
        System.out.println("循环方法猜测数字的位置为:"+index(array,33));
        System.out.println("递归方法猜测数字的位置为:"+binarySearch(array,0,array.length-1,33));
    }

 /**
     * 循环的方法
     * @param array
     * @param key
     * @return
     */
    public static int index(int array[],int key){

        int low = 0;
        int high = array.length - 1;
        int middle = 0;
       // int guess = array[middle];//猜测的数字

        if (key < array[low] || key > array[high] || low >high){
            return -1;
        }
        while (low <=high){ //循环结束的条件是左边等于右边,那就是中间要找的数字
            middle = (low + high)/2;
            int guess = array[middle];//猜测的数字
            if (guess < key){ //如果猜测的数字小于实际数字,low就要从middle+1开始
                low = middle + 1;
            }else if (guess > key){//如果猜测的数字大于实际数字,那么high就要从middle-1开始
                high = middle - 1;
            }else{
                return middle;
            }

        }
        return -1;
    }
    /***
     *递归的方式
     */
    public static int binarySearch(int[] arrays,int low,int high,int key){
        if (key < arrays[low] || key > arrays[high] || low >high){
            return -1;
        }
        int middle = (low + high) / 2;
        if (arrays[middle] > key){
           return  binarySearch(arrays, low, middle - 1, key);
        }else if (arrays[middle] < key){
           return  binarySearch(arrays, middle + 1, high, key);
        }else{
            return middle;
        }

    }
}

1. Time complexity analysis:

In the worst case, the time complexity of the two methods is the same: O(log2 N)


Best case O(1)

2. Space complexity analysis:

The space complexity of the algorithm is not to calculate the actual occupied space, but to calculate the number of auxiliary space units of the entire algorithm. The
loop method:
  because the auxiliary space is a constant level, the
  space complexity is O(1);
recursive method:

The number and depth of recursion are log2 N, and the auxiliary space required each time is constant level:
 space complexity: O(log2N)
 

Guess you like

Origin blog.csdn.net/qq_35207086/article/details/123326577