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

前端 未结 4 1643
孤独总比滥情好
孤独总比滥情好 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:14

    This can be done in O(n):

    1. Find median in O(n) (description is available in Wikipedia
    2. Put every element larger than the median on odd places and every smaller element - on even places

    Of course, this assumes that all elements are distinct, otherwise sometimes it will fail.

提交回复
热议问题