How to rearrange data in array so that two similar items are not next to each other?

后端 未结 8 1957
暗喜
暗喜 2020-12-31 12:00

Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can\'t be rearranged it can be put

8条回答
  •  醉话见心
    2020-12-31 12:19

    1. Sort your array
    2. Swap elements at small even indexes with their higher antipodal counterparts:

      for ( i=0; i < arr.length/2; i+=2 )
          arr.swap(i,arr.length-1-i);
      

    Edit: Okay, we should redefine the antipodal counterparts. Maybe this one is better: mixing the first and third quartile (denoted x, y in illustration), and mixing the second and third quartile (denoted u, v, w). Let the counterparts ascend parallel.

            25%  50%  75%
             |    |    |
        -----[----[----[----
        11122334455667788999
         x y u v w x y u v w  <-- u, v, w, x, y indicate swap positions
        16172839495161738495
    

提交回复
热议问题