我的稳定分区算法中的缺陷在哪里?

时间:2016-07-28 01:30:25

标签: javascript algorithm

尝试在JavaScript中递归编写它。我和以前一样得到了相同的数组(即没有任何变化)。

缺陷在哪里?

function unstable_partition ( arr, f )
{
      if(arr.length <= 1)
        return arr;
    var n = arr.length - 1;
    if(f(arr[0]))
        return unstable_partition(arr.slice(0,n),f).concat([arr[0]]);
    else if(!f(arr[n]))
        return [arr[n]].concat(unstable_partition(arr.slice(0,n - 1),f));
    else 
        return [arr[0]].concat(unstable_partition(arr.slice(1,n - 1)),f).concat([arr[n]]); 
}

var isEven = function(x) { return x % 2 == 0; }
var myArray = [1,2,3,3,4,5];
alert(unstable_partition(myArray,isEven).join(","));

1 个答案:

答案 0 :(得分:1)

切片不包含最后一个元素,不需要做&#34; -1&#34;你打电话的时候

更正后的代码: https://jsfiddle.net/n7g7yfju/

function unstable_partition ( arr, f )
{
      if(arr.length <= 1)
        return arr;
    var n = arr.length - 1;
    if(f(arr[0]))
        return unstable_partition(arr.slice(0,n),f).concat([arr[0]]);
    else if(!f(arr[n]))
        return [arr[n]].concat(unstable_partition(arr.slice(0,n),f));
    else 
        return [arr[0]].concat(unstable_partition(arr.slice(1,n),f)).concat([arr[n]]); 
}

var isEven = function(x) { return x % 2 == 0; }
var myArray = [1,2,3,3,4,5];
alert(unstable_partition(myArray,isEven).join(","));