All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars    
perplexus dot info

Home > Algorithms
Rotating an array (Posted on 2004-04-19) Difficulty: 2 of 5
I have an array such as A-B-C-D-E-F-G-H-I-J-K I want to rotate it N places to the right; for example, if N=3, the array should end I-J-K-A-B-C-D-E-F-G-H

Assume that the only available operation is a FLIP method that can invert any portion of the array. For example, applied to the original array FLIP(3,6) would produce A-B-F-E-D-C-G-H-I-J-K.

See The Solution Submitted by e.g.    
Rating: 4.0000 (13 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
Solution Algorithm | Comment 5 of 26 |
A "bubble sort" algorithm will do it.    
 
Start with the letter that is in relative position (11-N) (where A is originally in relative position 0). Flip this letter with its immediate left neighbor (11-N) times. (The letter moves through the array like a bubble rising to the surface). Then do the same with the letter in relative position (12-N), (13-N), ..., (10)  
 
For N=4: 
 
A-B-C-D-E-F-G-H-I-J-K
Flip H and its immediate neighbor on the left 7 times  
H-A-B-C-D-E-F-G-I-J-K
Flip I and its immediate neighbor on the left 7 times 
H-I-A-B-C-D-E-F-G-J-K
Flip J and its immediate neighbor on the left 7 times 
H-I-J-A-B-C-D-E-F-G-K
Flip K and its immediate neighbor on the left 7 times
H-I-J-K-A-B-C-D-E-F-G
 
 
 
 
 
 
 
 

 

Edited on April 19, 2004, 5:58 pm
  Posted by Penny on 2004-04-19 17:52:44

Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (0)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (15)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information