How to sort an array efficiently

后端 未结 4 406
鱼传尺愫
鱼传尺愫 2021-01-28 01:46

I\'m trying to sort an array [3,3,2,1,3,2,2,2,1] to [1,1,3,3,3,2,2,2,2].

I\'m trying to handle it using object, using the number as key, and th

4条回答
  •  梦毁少年i
    2021-01-28 02:42

    Assuming that the numbers are small non-negative integers, you can count them as you have done already, and then generate the result on the fly when someone (Array.from() in this example) requests for it, with a simple pair of loops:

    function *sortNums(array){
      let stats=[];
      for(var i of array)
        stats[i]=(stats[i]||0)+1;
    
      for(let i=0;i0){
          stats[i]--;
          yield i;
        }
    }
    
    console.log(Array.from(sortNums([3, 3, 10, 2, 1, 0, 3, 2, 1])).join());

    Of course it is possible to just collect the pieces into an array, in the direct, "traditional" way:

    let ret=[];
    for(let i=0;i0){
        stats[i]--;
        ret.push(i);//yield i;
      }
    return ret;
    

提交回复
热议问题