Gre*_*lin 11 algorithm performance in-place time-complexity data-structures
给定一个具有正整数和负整数的数组,将所有奇数索引元素移动到左侧,甚至将索引元素移动到右侧.
问题的难点在于在维持秩序的同时就地完成.
例如
7, 5, 6, 3, 8, 4, 2, 1
输出应该是:
5, 3, 4, 1, 7, 6, 8, 2
如果顺序无关紧要,我们可以使用快速排序的partition()算法.
如何在O(N)中完成?
算法就地,时间复杂度为O(N).
例:
0 1 2 3 4  5 6 7 8 9   10 11 (the original array)
0 1 2 3 4  5 6 7 8 9 # 10 11 (split to sub-arrays)
0 2 4 3 8  1 6 5 7 9 # 10 11 (first cycle leader iteration, starting with 1)
0 2 4 6 8  1 3 5 7 9 # 10 11 (second cycle leader iteration, starting with 3)
0 2 4 6 8  9 7 5 3 1 # 10 11(2nd half of 1st part& 1st half of 2nd part reversed)
0 2 4 6 8 10 1 3 5 7    9 11 (both halves reversed together)
这个算法的变化,不需要第5步:
这是不同的O(N log N)就地算法,它不需要数论证明:
例:
0  1   2 3   4 5   6 7  (the original array)
[0 2] [1 3] [4 6] [5 7] (first transposition)
[0 2] [4 6] [1 3] [5 7] (second transposition)
这个问题只是就地矩阵转置的一个特例.