递归选择排序(JS)

时间:2018-04-17 07:52:56

标签: javascript algorithm sorting recursion

我在JavaScript中编写递归选择排序。

期待行为:我希望函数selectionSort()按升序对数组中的值进行排序。

问题:我无法退出递归,而且我也不知道如何。

错误

  

Uncaught RangeError: Maximum call stack size exceeded

<小时/> 这是我的代码:

&#13;
&#13;
const findSmallestIndex = ( arr ) => {
    let smallest = arr[0];
    let smallestIndex = 0;
    let arrLen = arr.length;

    for ( let i = 0; i < arrLen; i++ ) {
        if ( arr[i] < smallest ) {
            smallest = arr[i];
            smallestIndex = i;
        }
    }
    return smallestIndex;
};

const selectionSort = ( arr ) => {
    let smallest = arr.splice( findSmallestIndex( arr ), 1 );
    return [smallest].concat( selectionSort( arr ) );
};

let arr = [23, 43, 23423, 66, 5, 57, 78, 0, 1];

console.log( selectionSort(arr) );
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

  1. 您必须添加完成递归的条件(所谓的基本案例if ( !arr.length ) return []
  2. arr.splice( findSmallestIndex( arr ), 1 )返回数组,不需要[smallest]... - 只需smallest.concat( selectionSort( arr ) )
  3. 改进:您的代码变异arr(由ftor注明),因此我们可以通过添加let newArray = Array.prototype.slice.call( arr );
  4. 来修复它

    /**
     * Finds smallest element of an aray
     * @param {Array} arr array for searching
     * @return {number} index of the smallest element in array
     */
    const findSmallestIndex = ( arr ) => {
        let smallest = arr[0];
        let smallestIndex = 0;
        let arrLen = arr.length;
    
        for ( let i = 0; i < arrLen; i++ ) {
            if ( arr[i] < smallest ) {
                smallest = arr[i];
                smallestIndex = i;
            }
        }
        return smallestIndex;
    };
    
    /**
     * Sorts recursively an array of numbers
     * @param {Array} arr An array of numbers
     * @return {Array} New sorted array
     */
    const selectionSort = ( arr ) => {
        if ( !arr.length ) return [];
        let newArray = Array.prototype.slice.call( arr );
        let smallest = arr.splice( findSmallestIndex( arr ), 1 );
        return smallest.concat( selectionSort( arr ) );
    };
    
    let arr = [23, 43, 23423, 66, 5, 57, 78, 0, 1];
    
    console.log( selectionSort(arr) );

    特色链接和条款

    1. Mastering recursive programming
    2. Array.prototype.splice()
    3. Base case - 解决方案可以非递归方式陈述的情况
    4. General (recursive) case - 的量,溶液以自身的较小版本来表示的情况下

答案 1 :(得分:0)

这是一种更高效的方法。

function selectionSort(arr) {

    var swap = function(x, y) {
        var temp = arr[y];
        arr[y] = arr[x];
        arr[x] = temp;
    }

    var sort = function(start) {
        if (start === arr.length) {
            return arr;
        }

        var min = start;

        for (var i = start + 1; i < arr.length; i++) {
            if (arr[i] < arr[min]) {
                min = i;
            }
        }

        swap(start, min);

        return sort(start + 1);
    }

    return sort(0);
}

selectionSort([23, 43, 23423, 66, 5, 57, 78, 0, 1]);