Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive method in the Java merge sort algorithm

Tags:

java

algorithm

I have the below merge sort code in my application. I am very confused on how the recursive method gets called again after it comes out of the if block when the if condition is not met.

I debugged my code, but I am still not getting it. The sort method that calls mergesort(0, number - 1) starts first at mergesort(0, 5). low is less than high, middle is 2, so mergesort(0, 2) is run next. This goes on until we have mergesort(0, 0) in which case low is not less than high, so it comes out of the if block. But when I debug, the method returns, and it starts again after mergesort(0, 0) case. How does the call happen again?

    public class MergeSort {
        private int[] numbers;
        private int[] helper;

    private int number;


    public int[] sort(int[] values) {
        this.numbers = values;
        number = values.length;
        this.helper = new int[number];
        return mergesort(0, number - 1);
    }

    private int[] mergesort(int low, int high) {
        // check if low is smaller then high, if not then the array is sorted
        if (low < high) {
            // Get the index of the element which is in the middle
            int middle = low + (high - low) / 2;
            // Sort the left side of the array
            mergesort(low, middle);
            // Sort the right side of the array
            mergesort(middle + 1, high);
            // Combine them both
            merge(low, middle, high);
        }
        return numbers;
    }

    private int[] merge(int low, int middle, int high) {

        // Copy both parts into the helper array
        for (int i = low; i <= high; i++) {
            helper[i] = numbers[i];
        }

        int i = low;
        int j = middle + 1;
        int k = low;
        // Copy the smallest values from either the left or the right side back
        // to the original array
        while (i <= middle && j <= high) {
            if (helper[i] <= helper[j]) {
                numbers[k] = helper[i];
                i++;
            } else {
                numbers[k] = helper[j];
                j++;
            }
            k++;
        }
        // Copy the rest of the left side of the array into the target array
        while (i <= middle) {
            numbers[k] = helper[i];
            k++;
            i++;
        }
        return numbers;

    }
}
like image 937
rickygrimes Avatar asked May 03 '26 15:05

rickygrimes


1 Answers

This is because the mergesort method calls itself twice. You can print out the stack to see what happens.

For example, when call mergesort(0,1), the method will call mergesort(0,0) first and then mergesort(1,1).

like image 64
locoyou Avatar answered May 05 '26 03:05

locoyou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!