Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
1.4 kB
0
Indexable
Never
module.exports = { 
    solve: function(A) {
        function merge(a) {
            if (a.length <= 1) {
                return a;
            }

            let n = a.length;
            let mid = Math.floor(n / 2);

            let left = a.slice(0, mid);
            let right = a.slice(mid);

            let sortedLeft = merge(left);
            let sortedRight = merge(right);

            return mergeSortedArray(sortedLeft, sortedRight);
        }

        function mergeSortedArray(left, right) {
            let result = [];
            let leftIndex = 0;
            let rightIndex = 0;

            while (leftIndex < left.length && rightIndex < right.length) {
                if (left[leftIndex] < right[rightIndex]) {
                    result.push(left[leftIndex]);
                    leftIndex++;
                } else if (right[rightIndex] < left[leftIndex]) {
                    result.push(right[rightIndex]);
                    rightIndex++;
                }
            }

            while (leftIndex < left.length) {
                result.push(left[leftIndex]);
                leftIndex++;
            }

            while (rightIndex < right.length) {
                result.push(right[rightIndex]);
                rightIndex++;
            }

            return result;
        }

        return merge(A);
    }
};
Leave a Comment