javaalgorithmmergesortdivide-and-conquer

I can't figure out the problem with this merge sort algorithm


I am trying to learn data structures and algorithms and I have been enjoying the process. I started to look into how Merge Sort works and wanted to implement it. This is my code, for some reason I can't figure out why my outputs are messed up!

    public static void Merge(ArrayList<Integer> arr, int low, int mid, int high) {
        int left = low;
        int rightPointer = mid + 1;

        ArrayList<Integer> new_list = new ArrayList<>();

        while (left <= mid && rightPointer <= high) {
            if (arr.get(left) <= arr.get(rightPointer)) {
                new_list.add(arr.get(left));
                left++;
            } else {
                new_list.add(arr.get(rightPointer));
                rightPointer++;
            }
        }

        while (left <= mid) {
            new_list.add(arr.get(left));
            left++;
        }

        while (rightPointer <= high) {
            new_list.add(arr.get(rightPointer));
            rightPointer++;
        }

        for (int ele : new_list) {
            System.out.print(ele + " ");
        }
        System.out.println();
    }

    public static void MergeSort(ArrayList<Integer> arr, int low, int high) {
        if (low >= high)
            return;
        int mid = (low + high) / 2;

        MergeSort(arr, low, mid);
        MergeSort(arr, mid + 1, high);
        Merge(arr, low, mid, high);
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>(
                Arrays.asList(25, 10, 3, 50, 24, 14, 8, 22, 35, 42, 10, 5, 18, 29, 50));

        MergeSort(list, 0, list.size() - 1);
    }

This is my output, (printing each call of the merge function):

10 25 
3 50 
3 25 10 50 
14 24 
8 22 
8 22 24 14 
24 14 8 22 25 10 3 50 
35 42 
5 10 
10 5 35 42 
18 29 
18 29 50 
18 29 35 42 10 5 50 
25 10 3 35 42 10 5 18 29 50 24 14 8 22 50

What am I doing wrong here? I have tried asking chatGPT and the response was that it couldn't find any errors from the given code!

I have tried rewriting the entire code on python and figured out that the list is not being correctly sorted as it's being inserted into the newly "sorted" array. But I don't know how to solve this.


Solution

  • Your code looks almost correct, you are simply not updating the original array with the sorted elements. After merging the element into the new list, you need to copy them back into the original array. I have tested your code, and it looks correct after adding this loop at the end of the Merge method:

        for (int i = 0; i < new_list.size(); i++)
            arr.set(low + i, new_list.get(i));