How to rearrange an array in such a way that each element is greater/smaller than its neighbours

前端 未结 4 1657
孤独总比滥情好
孤独总比滥情好 2020-12-29 10:50

For example, if the numbers are:

30, 12, 49, 6, 10, 50, 13

The array will be:

[10, 6, 30, 12, 49, 13, 50]
<
4条回答
  •  误落风尘
    2020-12-29 11:08

    Assuming the numbers are all distinct, the easiest way is probably to sort the numbers then interleave the first and second halves of the sorted list. This will guarantee the high/low/high/low/high/low/.... pattern that you need.

    This algorithm is O(n log n) which should be efficient enough for most purposes, and may benefit from optimised sorting routines in your standard library.

    If the numbers are not distinct, then it is possible that there is no solution (e.g. if the numbers are all equal)

提交回复
热议问题