Search code examples
algorithmcomplexity-theorytime-complexitydivide-and-conquer

what is the complexity of recursive linear search ( using divide and conquer technique )?


wanted to analyse the complexity of recursive linear search ( using divide and conquer technique ). Is it log(n) or n ? if not log(n) then what is the actually complexity and how ?

int linear_search(int *a,int l,int h,int key){
    if(h == l){
        if(key == a[l])
            return l;
        else 
            return -1;
    }       
    int mid =(l+h)/2;
    int i = linear_search(a,l,mid,key);
    if(i == -1)
         i = linear_search(a,mid+1,h,key);
    return i; 
}

Solution

  • Yes, it's O(n). What the recursive method does is just a loop, so you would be better off using a real loop:

    int linear_search(int *a,int l,int h,int key){
      for (int i = l; i <= h; i++) {
        if (a[i] == key) return i;
      }
      return -1;
    }
    

    If you want to use recursion to avoid a loop, there is one worse way of doing it, sometimes found in (bad) examples showing recursion:

    int linear_search(int *a,int l,int h,int key){
      if (l > h) {
        return -1;
      } else if (a[l] == key) {
        return l;
      } else {
        return linear_search(a, l + 1, h, key);
      }
    }
    

    It's still O(n), but it's worse because it will fill the stack if the array is too large. The divide and conquer approach at least will never nest deeper than the number of bits in an integer.