1

I know the mergeSort function takes O(logn) and merge function takes O(n) and therefore total complexity is O(nlogn).

void mergeSort(int arr[], int l, int r){
    if(l >= r){
        return;
    }
    int m = (l + r) / 2;
    mergeSort(arr, l, m);
    mergeSort(arr, m+1, r);
    merge(arr, l, m, r);  
}

Now let's say I use the same logic for implementing the below code for sum of array elements

int arraySum(int arr[], int l, int r){
    if(l == r){
        return arr[l];
    }
    int mid = (l + r) / 2;
    int one = arraySum(arr[], l, mid);
    int two = arraySum(arr[], mid + 1, r);
    return one + two;
}

Now this arraySum() function is identical to the mergeSort() except for the merge() ie. O(n) part. So, shouldn't the time complexity of arraySum() be O(logn). But I know this is not possible because there are n elements and each element is accessed in O(1) and it must be O(n). Now I am confused between these two logics. Why does the mergeSort() takes O(logn) [Ignoring the merge() function] and this arraySum() takes O(n), even though they are identical.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

3

arraySum has time complexity O(n), while mergeSort() has time complexity O(n log(n)). Note that each instance of each instance of | return one + two; | has complexity O(1), while each instance of | merge(arr, l, m, r); | has complexity O(r-l).

For n elements, arraySum will perform n-1 additions, while mergeSort will perform n ⌈log2(n)⌉ moves.

rcgldr
  • 27,407
  • 3
  • 36
  • 61