Fractal top down mergesort

I am trying to include a recursive sort function in part of the mergesort algorithm. Here I have a code that I am almost sure of correct (after the 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 splits each submassing into two smaller subarrays, repeating this until the subarrays are one in length (and, by definition, sorted), and then merged. However, the actual METHOD that this sorting function uses to achieve this is hard for me to follow. Maybe because I'm not used to recursive functions, but I was wondering if anyone would be able to illuminate the order of operations and what arguments arise during the first merge.

For example, when he calls a FIRST recursive call for sorting (a, aux, low, mid) - he aborts the operation and does not proceed to the second sorting and the merge functions below, instead he immediately calls the sorting with the new parameters? When in this case the second call will be sorted; sort (a, aux, mid + 1, high); occur?

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

+4
source share
2 answers

FIRST- (a, aux, low, mid) - , ?

  • . () , , .

; sort (a, aux, mid + 1, high); ?

  • . ( ).
+2

, , :

 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. 

, , .

+1

Source: https://habr.com/ru/post/1667989/


All Articles