Re: circular shift array



dan <dagoldman@xxxxxxxxx> writes:

On Jul 30, 7:36 pm, Barry Schwarz <schwa...@xxxxxxxxx> wrote:
On Mon, 30 Jul 2007 22:04:42 -0500, "Bint" <b...@xxxxxxxx> wrote:
Hi,

What is a simple way to shift the elements in an array, circularly? Is
there a way to do it so that you don't need a separate storage array?

IE I want to shift array A{1,2,3,4,5,6,7,8} by 3 to the right. The result
would be B{6,7,8,1,2,3,4,5)

You don't need a separate array; one temporary object to hold the
rightmost value is sufficient.

Save rightmost value
Loop through array from right to left starting at next to
rightmost value
Save value in next element to the right
Store saved value in first element
Repeat as often as necessary.

You could make a function out of it (or even a macro)

void rshift_int(int array[], size_t num_elements, int
iterations){...}

Remove del for email

Barry is correct. I did this kind of thing.

One suggestion. If you have a bunch of arrays, instead of a temporary
object, you may want to make each array one longer than needed, and
use the extra element as the temporary object. It may make your code
easier to read and maintain.

Daniel Goldman


or just have the array double its normal size with duplicate copies and
merely shuffle a pointer to the first element .... no Memory move at all
then.
.



Relevant Pages

  • Re: is there a compiler warning for this piece of code ?
    ... Thanks for your thoughts - I think your speculation as to the history of the ... An element of a char array cannot be NULL; ... > _address_ of the first element. ... >> Incorrect. ...
    (microsoft.public.vc.language)
  • Re: Fast lookup of ranges
    ... I have a peculiar (atleast to me) problem before my hand. ... big table with numeric ranges in each row. ... and the first element is always less than ... Chose an array length N, the larger the faster we can search. ...
    (comp.programming)
  • Re: writing get_script()
    ... to the highest index. ... remove the first element from an array. ... print "$verse $script\n"; ...
    (comp.lang.perl.misc)
  • Re: Please, I am going insane: First element access causing ArrayIndexOutOfBoundsException:0
    ... I have an array created that has ... I feed the results of the query into the array... ... same error when i try to access the first element. ... its own prepared statement and resultset and it fixed the problem. ...
    (comp.lang.java.programmer)
  • Re: Invisible Array Loop Counter?
    ... What we see here is that in the first method, the first element you tried ... and the third element became a reference ... from the array. ...
    (comp.lang.perl.misc)