Skip to content

JAVA: Merge Sort

Roberto Fronteddu edited this page Sep 3, 2024 · 2 revisions
import java.util.Arrays;

public class MergeSort
{
    public static int[] mergeSort (int[] input) {
        if (input.length <= 1) {
            return input;
        }

        int midPoint = input.length / 2;
        int[] left = mergeSort (Arrays.copyOfRange (input, 0, midPoint));
        int[] right = mergeSort (Arrays.copyOfRange (input, midPoint, input.length));
        return merge (left, right);
    }

    public static int[] merge (int[] left, int[] right) {
        int[] ret = new int[left.length + right.length];

        int leftIndex = 0;
        int rightIndex = 0;
        int retIndex = 0;

        // place elements of l and r in order in ret
        while (leftIndex < left.length && rightIndex < right.length) {
            if (left[leftIndex] < right[rightIndex]) {
                ret[retIndex++] = left[leftIndex++];
            } else {
                ret[retIndex++] = right[rightIndex++];
            }
        }
        // append the rest of left
        while (leftIndex < left.length) {
            ret[retIndex++] = left[leftIndex++];
        }
        // append the rest of right
        while (rightIndex < right.length) {
            ret[retIndex++] = right[rightIndex++];
        }
        return ret;
    }
}
Clone this wiki locally