0

I understand how the merge part of the merge sort works, however, for some reason I just cannot wrap my head around the recursive/divide part that occurs before the merge function is called. Using the sample code below, I tried tracing the value of different variables but could not fully understand what is happening.

public void sort(int arr[], int l, int r) { 
    if (l < r) 
    { 
        // Find the middle point 
        int m = (l+r)/2; 

        // Sort first and second halves 
        sort(arr, l, m); 
        sort(arr , m+1, r); 

        // Merge the sorted halves 
        merge(arr, l, m, r); 
    } 

}

To me it seems like m keeps getting passed into sort until it becomes 0, so it seems like the 2nd sort() call and the merge() call never execute. Can someone explain the steps that are taken?

2
  • 1
    This would be a great time to learn how to use the java debugger. It would allow you to view the code and the variables in real time so that you can trace exactly everything that's happening as it happens. Commented Feb 6, 2020 at 22:38
  • If you are asking about Java's built in sort, it uses Timsort, which is a hybrid insertion + bottom up merge sort. A simpler variation is also a hybrid insertion + bottom up merge sort. An array of n elements is treated as n/k groups of k elements, and each group of k elements is sorted using insertion sort, then the now sorted groups are repeatedly merged breadth first to complete the sort. There's no recursive dividing (generation of indexes) involved. Commented Feb 7, 2020 at 3:47

1 Answer 1

2

Take the following array:

[4][2][5][1][3]

We're going to split it in half:

[4][2][5]    [1][3]

And again:

[4][2]    [5]    [1]    [3]

And again:

[4]    [2]    [5]    [1]    [3]

Notice how we now have 5 sorted arrays (each of length 1). Now it's time to merge them together, sorting as we go. It's a very simple (read: low time-complexity) operation to merge two sorted arrays into a new sorted array:

[2][4]    [1][5]    [3]

Now we have 3 sorted arrays. Let's merge them again:

[1][2][4][5]    [3]

And one final time:

[1][2][3][4][5]

It's now been sorted.

Sign up to request clarification or add additional context in comments.

1 Comment

So I understand the concept of how the array should be split, what I would like to know what is happening in each step as the code is being executed. I think the problem is I can’t seem to tie the code to the concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.