简体   繁体   中英

Recursive top down mergesort

I'm trying to get my head round the recursive sort function that's part of the mergesort algorithm. Here's the code I have, which I'm almost certain is correct (following an online course).

    private static void sort(Comparable[] a, Comparable[] aux, int low, int high) {
         if (high <= low) return;
         int mid = low + (high - low) / 2;
         sort (a, aux, low, mid);
         sort (a, aux, mid+1, high);
         merge(a, aux, low, mid, high);
   }

I understand what mergesort does- it breaks each subarray down into 2 smaller subarrays, repeating this until the subarrays are of length one (and by definition sorted), and then merges. However, the actual METHOD that this sort function uses to accomplish this is hard for me to follow. Maybe because I'm not used to recursive functions, but I was wondering if anyone can illuminate the order of operations and what the arguments are when the first merge occurs.

For example, when it hits the FIRST recursive call to sort(a, aux, low, mid) - does it break operation and not proceed to the second sort and the merge functions below, instead immediately calling sort again with the new parameters? When, in this case, would the second call to sort; sort(a, aux, mid+1, high); occur?

Thanks for any help. This is the first time I've posted here, if there are any formatting issues please let me know.

When it hits the FIRST recursive call to sort(a, aux, low, mid) - does it break operation and not proceed to the second sort and the merge functions below, instead immediately calling sort again with the new parameters?

  • Yes. it calls the function again ( Recursion ) for the new parameters, go down until it sorts that part.

When, in this case, would the second call to sort; sort(a, aux, mid+1, high); occur?

  • After the first call is done executing. (When the first part is finished sorting).

Comments explaining each step in case you didn't get any:

 if (high <= low) return; // if your high and low numbers are the same then this part of the loop is finished and it will start going back up
 int mid = low + (high - low) / 2;//sets mid
 sort (a, aux, low, mid);//recursively calls itself so that it will eventually hit the first if. This handles from low to mid
 sort (a, aux, mid+1, high); //this handles from mid+1 to high
 merge(a, aux, low, mid, high); //This is where the merge starts. 

I find it helps to run a simple example and run through it over pen and paper if you're really having a hard time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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