All files / algorithms/sort/src merge.ts

100% Statements 29/29
100% Branches 6/6
100% Functions 1/1
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41  5x 5x   5x 17x 8x 8x 8x 8x 8x 8x 8x 8x 8x 16x 1x 1x     15x 15x   16x   8x 12x 12x 12x   8x 1x 1x 1x     17x   5x    
// @src: https://www.jesuisundev.com/comprendre-les-algorithmes-de-tri-en-7-minutes/
export const sortMerge = <Element>(array: Element[]): Element[] => {
    if (array.length > 1) {
        const middleIndex = Math.floor(array.length / 2);
        const leftSide = array.slice(0, middleIndex);
        const rightSide = array.slice(middleIndex);
 
        sortMerge(leftSide);
        sortMerge(rightSide);
 
        let leftIndex = 0;
        let rightIndex = 0;
        let globalIndex = 0;
 
        while (leftIndex < leftSide.length && rightIndex < rightSide.length) {
            if (leftSide[leftIndex] < rightSide[rightIndex]) {
                array[globalIndex] = leftSide[leftIndex];
                leftIndex++;
            } else {
                array[globalIndex] = rightSide[rightIndex];
                rightIndex++;
            }
            globalIndex++;
        }
 
        while (leftIndex < leftSide.length) {
            array[globalIndex] = leftSide[leftIndex];
            leftIndex++;
            globalIndex++;
        }
 
        while (rightIndex < rightSide.length) {
            array[globalIndex] = rightSide[rightIndex];
            rightIndex++;
            globalIndex++;
        }
    }
 
    return array;
};