简体   繁体   English

以下搜索算法的时间复杂度是多少

[英]What will be the time complexity of below search algorithm

I am trying to make a program that recursively searches for an element by dividing the array into half, can you tell what will be time complexity of the below code?我正在尝试通过将数组分成两半来创建一个递归搜索元素的程序,你能说出下面代码的时间复杂度吗?

public  boolean search(List<Integer> A, int B,int l,int r) {
        if(l==r) {
            if(A.get(l)==B) {
                System.out.println("Found at index : "+l);
                return true;
            }else {
                return false;
            }
        }
        int mid = (l+r)/2;
        boolean a = search(A, B,l,mid);
        boolean b = search(A, B,mid+1,r);
        return a||b;
    }

above code, l is left most index and r is right most index for example上面的代码,例如 l 是最左边的索引,r 是最右边的索引

List A = new ArrayList<>(Arrays.asList(2,5,1,65,8,4));列表 A = new ArrayList<>(Arrays.asList(2,5,1,65,8,4));

for the above arraylist we are searching element 4 so the method will be-对于上述 arraylist,我们正在搜索元素 4,因此该方法将是-

search(A, 4,0,A.size()-1)

The time complexity of this algorithm is O(n) because it will go through each element in the list.该算法的时间复杂度为 O(n),因为它将 go 遍历列表中的每个元素。

The space complexity is O(log(n)) because of the recursive calls putting in the stack at most log(n) recursive calls before backtracking.空间复杂度为 O(log(n)),因为递归调用在回溯之前最多放入堆栈 log(n) 递归调用。 Why?为什么? Because each recursive call will 'divide' the list in half until the last element in that search (sub-list) is processed.因为每个递归调用都会将列表“分成”两半,直到该搜索(子列表)中的最后一个元素被处理。 Then it will return/backtrack and continue the search on another part of the list.然后它将返回/回溯并继续搜索列表的另一部分。 Since it backtracks while halving until there is one element left in that sublist, it will never put all the elements in the stack of the recursive calls at once.由于它在减半时回溯,直到该子列表中剩下一个元素,所以它永远不会一次将所有元素放入递归调用的堆栈中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM