Professional Documents
Culture Documents
Vector Rotation: 2000, Lucent Technologies Pearls-2-1
Vector Rotation: 2000, Lucent Technologies Pearls-2-1
Pearls-2-1
The Problem The Problem Rotate vector x [ n ] left by d positions. For n=8 and d=3, change abcdefgh to defghabc. Constraints: O ( n ) time, O ( 1 ) extra space. Pricey Solutions Store d in intermediate vector, shift the rest, store back. [O ( n ) extra space.] Rotate by 1 d times. [O ( n ) time.]
Pearls-2-2
The Code for i = [0, gcd(d, n)) /* move i-th values of blocks */ t = x[i] j = i loop k = j + d if k >= n k -= n if k == i break x[j] = x[k] j = k x[j] = t
Pearls-2-3
The Block-Swap Algorithm The Idea: Change ab to ba If a is shorter, divide b into b l and b r . Swap a and b r to change ab l b r into b r b l a. Recur on pieces of b. The Code if d == 0 || d == n return i = p = d j = n - p while i != j if i > j swap(p-i, p, j) i -= j else swap(p-i, p+j-i, i) j -= i swap(p-i, p, i)
Pearls-2-4
The Reversal Algorithm The Idea Reverse a to get a r b. Reverse b to get a r b r . Reverse all to get ( a r b r ) r = ba. The Code /* rotate abcdefgh left three */ reverse(0, d-1) /* cbadefgh */ reverse(d, n-1) /* cbahgfed */ reverse(0, n-1) /* defghabc */ Doug McIlroys Handwaving Description
1 2 3 4 5 7 8 9 10 6 5 4 3 2 10 9 8 7 5 4 3 2 7 8 9 10 6
7 8 9 10
1 6
2 3 4 5
Flip Both
Pearls-2-5
150
0 1 10 20 30 40 Rotation Distance 50
Pearls-2-6
Pearls-2-7