Merge Sort Doubt1

I have used the same approach used in the video but it’s giving me TLE. How is that possible if the complexity of the algorithm is o(nlogn). Please explain?

code: https://github.com/kush1912/Data-Structures-and-Algorithms-in-C-/blob/master/Recursion/mergesort.cpp

There are many reasons due to which your code would not work correctly.
I have done the modifications in your code as follow:

  1. TLE
    [you have to start inserting from the s index but you are doing it from the 0th index.]

    for( int i=s;i<=e;i++)
    {
    arr[i] = temp[i-s];
    }

  2. Run time error
    [ the values of e and s can be other than n-1 and 0 resp. (you were not considering this)]

    int mid = (s+e)/2;
    int i=s,j=mid+1,k=0;
    int n=e-s+1;
    int temp[n];

    // k should be initialized with 0 as you will insert in it from the starting index
    // temp can have more than 100 elements

  3. Wrong Output:
    [You are printing the output in wrong format]

    for(int i = 0;i<n;i++)
    {
    cout<<arr[i]<<" ";
    }

Click here to see the modified code.

Hope, this would help.
Give a like, if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.