排序多维数组的最佳方法

时间:2014-07-26 15:32:41

标签: javascript jquery arrays algorithm sorting

我有一个多维数组

array = [];
array[0] = [1,3,8,4,9,5];
array[1] = [5,9,4,2,9,3,0];
array[2] = [5,2,6,1,3,8,4,9,5,17,2,9,3,0];
array[3] = [-1,0,20,6];

我想对它进行排序以获得此结果

[
       [-1,0,0,0,1,1],
       [2,2,2,3,3,3,3],
       [4,4,4,5,5,5,5,6,6,8,8,9,9,9],
       [9,9,17,20]
]

我已经定义了这个帮助我得到这个结果的函数

Array.prototype.sort_multi = function()
{
    var arr = [];
    this.forEach(function(element_arr,index_arr,array_arr)
    {
        element_arr.forEach(function(element,index,array)
        {
            arr.push(element);
        });
    });
    arr.sort(function (a, b) { return a - b;});
    this.forEach(function(element_arr,index_arr,array_arr)
    {
        element_arr.forEach(function(element,index,array)
        {
            array_arr[index_arr][index] = arr.shift();
        });
    });
    return this;
}

我的问题是:有一种简单的方法吗?例如使用函数sort或简单算法......?

1 个答案:

答案 0 :(得分:4)

sort_multi()的略微简化(效率稍高)版本:

基本上这里发生的是:

  1. 原始数组中的项目合并为一个大数组(以便于排序)
  2. 我们在加入
  3. 时记录原始子数组的长度
  4. 以数字方式对连接的数组进行排序(如您发布的代码中所示)
  5. 按照原始子数组的长度分割已排序的大数组
  6. 返回结果
  7. 为什么这比原始代码更有效:

    1. 原始代码按元素迭代每个子数组元素以进行连接。这不是必需的,因为我们已经完全实现了concat()
    2. 原始代码在拆分连接/排序数组时再次逐个元素地迭代 - 不需要,因为我们有splice()

    3. Array.prototype.sort_multi = function() {
          var joined = [], lens = [], result = [];
          this.forEach(function(item) {
              joined = joined.concat(item);
              lens.push(item.length); // store the initial lengths
          });
          joined = joined.sort(function (a, b) { return a - b;}); // sort numerically
          lens.forEach(function(item) { // for each length in lens
              result.push(joined.splice(0, item));
          });
          return result;
      }