Reordering of array elements

前端 未结 4 413
予麋鹿
予麋鹿 2020-12-02 19:24

Given an array

[a1 a2 a3 ... an b1 b2 b3 ... bn c1 c2 c3 ...cn]

without using extra memory how do you reorder into an array



        
4条回答
  •  时光说笑
    2020-12-02 19:56

    You can calculate each item's target position based on its index.

    groupSize = N/3
    group = i/groupSize
    rank = i - group * groupSize
    dest = rank * 3 + group
    

    You can use this calculation with a cycle sort to put each element in its proper place in linear time. The only issue is tracking which items are already in place. All you need for that is N bits. With certain types of data, you can "steal" a bit from the data item itself. For instance you can use the high bit of ASCII data, or the low byte of word-aligned pointers.


    Alternately, you can do it without any extra bits at the expense going to polynomial time. Reverse the calculation, so you can find the original source index of each item in the final array.

    source = i % groupSize + groupSize * (i/groupSize) ;  //integer division
    

    Now walk forward through the array, swapping every item with the one from the source. The trick is that any time the source index is less than the current position (meaning it has already been swapped out), you need to follow the trail until you find its current location

    getSource(i):
       s = i % groupSize + groupSize * (i/groupSize)
       while (s

提交回复
热议问题