簡體   English   中英

在 JavaScript 中將 N 個未排序數組合並為 1 個排序數組的最快方法是什么?

[英]What is the fastest way to merge N unsorted arrays into 1 sorted array in JavaScript?

我在 JavaScript 中將 N 個未排序數組合並為 1 個排序數組時遇到問題。

我知道我可以快速連接然后排序,但效率在這里很重要。

我有從 api 返回的數組(我不能確保它們到達排序),需要以 1 個排序數組結束。 我的第一直覺是盡量不要重新發明輪子,而是嘗試找到一種方法將它們可靠地分類到輸出數組中。 我想我會嘗試對每一個進行排序,然后利用GeeksForGeeks上的算法。 這要求數組按順序排列,所以我首先單獨對數組進行排序

我沒有花太多時間在 C++ 上,所以我花了一些時間嘗試在 JavaScript 中重新實現它:

const TinyQueue = require('tinyqueue'); // const Heap = require('heap');

//typedef pair<int, pair<int, int> > ppi; 
const pair = (val1, val2) => ({ first: val1, second: val2 });
const ppi = (val1, [val2a, val2b]) => pair(val1, pair(val2a, val2b));
//console.log(ppi('a', ['b', 'c'])) -> { first: 'a', second: { first: 'b', second: 'c' } }

// This function takes an array of arrays as an 
// argument and all arrays are assumed to be 
// sorted. It merges them together and prints 
// the final sorted output.  
function mergeKArrays(arr) {
  const output = [];
  queue = new TinyQueue();

  for (var i = 0, len = arr.length; i < len; i++) queue.push(ppi(arr[i][0], [i, 0]));

  while(queue.length) {
    let curr = queue.pop();
    // i ==> Array Number 
    // j ==> Index in the array number   
    let i = curr.second.first;   
    let j = curr.second.second;

    output.unshift(curr.first); 

    // The next element belongs to same array as current. 
    if (j + 1 < arr[i].length) queue.push(ppi( arr[i][j + 1], [ i, j + 1]));
  }

  return output;
}
// -- Test Data --
const unsortedArrays = [
  [12, 2, 6], 
  [9, 1], 
  [2000, 23, 34, 90]
];
const sortedArrays = unsortedArrays.map(array => array.sort((a,b) => a - b));

console.log(sortedArrays);
const mergedArr = mergeKArrays(sortedArrays);

console.log(mergedArr);

Geeks for Geeks 算法 此代碼在 repl.it 上共享

所以輸入是[ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ]

預期輸出為[ 1, 2, 6, 9, 12, 23, 34, 90, 2000 ]

實際輸出為[ 9, 2000, 1, 90, 12, 34, 6, 23, 2 ]

這里出了什么問題? 如果這有效,是否有更有效的方法將 N 個未排序的數組合並為 1 個排序的數組?

我會先展平數組然后排序

 let input = [ [ 2, 6, 12 ], [ 1, 9 ], [ 23, 34, 90, 2000 ] ];
 let output = input.reduce((complete, next) => complete.concat(next), []) // to flatten
      .sort((a,b) => a-b) //to sort

根據文章的大陣列谷歌的V8引擎采用快速排序,這需要大約O(n.log(N))

V8 使用Timsort ,它利用了自然運行。 所以,你可以扁平化和排序:

 const unsortedArrays = [ [12, 2, 6], [9, 1], [2000, 23, 34, 90] ]; const sorted = unsortedArrays.flat().sort((a, b) => a - b); console.info(sorted);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM