Search code examples
javascriptarrayssortingrecursionbubble-sort

Turn a binary tree array into a one-dimensional array JavaScript


I'm attempting to program bubble sort recursively. This is my code so far:

function recursive_bubble_sort(array) {
    if (array.length === 1) {
        return array;
    }

    for (var i = 0; i < array.length - 1; i++) {
        if (array[i] > array[i + 1]) {
            var temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    return [recursive_bubble_sort(array.splice(0, array.length - 1)), array[array.length -1]];
}

Technically it sorts the array but the return is not a one-dimensional array, instead it's in a reverse binary tree structure.

If the given array is [ 8, 2, 5, 1 ],
the output would be [ [ [ [ 1 ], 2 ], 5 ], 8 ].
How can I change the code so the output is like this: [ 1, 2, 5, 8 ]?


Solution

  • The problem is the return statement

    return [recursive_bubble_sort(array.splice(0, array.length - 1)), array[array.length -1]];
    

    However, since recursive_bubble_sort either returns a single element recursive_bubble_sort or an array (the other return), you need to handle both.

    One easy way is to just use Array#concat - if you give it a single element, it adds it to a the array, if you give it an array, it adds all elements, instead. This ensures the result is always flat:

    You can instead

    function recursive_bubble_sort(array) {
        if (array.length === 1) {
            return array[0];
        }
    
        for (var i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                var temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
            }
        }
    
        return [].concat(recursive_bubble_sort(array.splice(0, array.length - 1)), array[array.length -1]);
    }
    
    console.log(recursive_bubble_sort([ 8, 2, 5, 1 ]))