, O (1) O (n) , . , , , x2, , , , (.. X3), x2.
, x3 ..
, , ( ).
:
x1 x2 x3 y1 y2 x2 is out of place so take it into temp storage
x1 -- x3 y1 y2 temp: x2 needs to go where x3 currently is
x1 -- x2 y1 y2 temp: x3 needs to go where y2 currently is
x1 -- x2 y1 x3 temp: y2 needs to go where y1 currently is
x1 -- x2 y2 x3 temp: y1 needs to go into the empty slot
x1 y1 x2 y2 x3 all elements in place -> finished
0, k
2k if k < n
2(k-n) + 1 if k >= n
, , . , n = 4, 3 :
0 -> 0
1 -> 2 -> 4 -> 1
3 -> 6 -> 5 -> 3
.
, , , O (n) .