Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Vector Rotation The Problem Three Algorithms Implementations

From Programming Pearls, Copyright 2000, Lucent Technologies

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.]

From Programming Pearls, Copyright 2000, Lucent Technologies

Pearls-2-2

A Juggling Algorithm The Idea (n = 12, d = 3)


t

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

From Programming Pearls, Copyright 2000, Lucent Technologies

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)

From Programming Pearls, Copyright 2000, Lucent Technologies

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 Left Hand

Flip Right Hand

Flip Both

From Programming Pearls, Copyright 2000, Lucent Technologies

Pearls-2-5

An Experiment on Run Times

n = 10 6 , 400MHz Pentium II.


200 Juggling

150

Nanosecs 100 Per Element

Reversal 50 Block Swap

0 1 10 20 30 40 Rotation Distance 50

From Programming Pearls, Copyright 2000, Lucent Technologies

Pearls-2-6

From Programming Pearls, Copyright 2000, Lucent Technologies

Pearls-2-7

You might also like