Thread: Shifting arrays K positions without using additional memory

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    43

    Shifting arrays K positions without using additional memory

    I have been tasked with a program that shifts an array k position without additional memory. I don't know what kind of memory are they talking about, because I will obviously have to use one index value for the loop... Anyway, here is an example:
    shiftArray(numbers, k) for 1 2 3 4 5 6 7 8 and k = 3 should give: 4 5 6 7 8 1 2 3.

    The problem is simple, however, after constantly failing at minor things, I cannot think clear anymore. Here is my full code. The result for 1 2 3 4 5 6 7 8 is 5 2 3 4 5 6 7 8. I have discovered that the problem is in the if statement, but I cannot figure out why. I know the code is cluttered for the function, but that is only because I do not want to store the size into a variable, because of that memory condition...

    If you cannot find a way around the program, could you give me another suggestion if there is a more efficient way? Thank you very much.

    Cosmin

    Code:
    #include <iostream>
    
    using namespace std;
    
    void shiftArray(int numbers[], int k)
    {
    	int index;
    	for(index = 0; index < (int)(sizeof numbers)/(sizeof numbers[0]);  index++)
    	{
    		if(index >= numbers[(int)(sizeof numbers)/(sizeof numbers[0]) - k])
    		{
    			numbers[index] = numbers[index % k];
    		}
                                    else
                                    {
                                                    numbers[index] = numbers[index + k];
                                    }
    	}
    }
    
    int main(int argc,char* argv) 
    {
    	int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8};
    	int k = 4;
    	shiftArray(numbers, k);
    	int i;
    	for(i = 0; i < (int)(sizeof numbers)/(sizeof numbers[0]); i++)
    	{
    		cout << numbers[i] << " ";
    	}
    	cout << endl;
    
    	return 0;
    }
    Last edited by Veneficvs; 03-29-2011 at 06:06 PM. Reason: I forgot to add else

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Fragmentation with Dynamic FIFO Queue
    By fguy817817 in forum Linux Programming
    Replies: 17
    Last Post: 10-31-2009, 04:17 AM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Reallocating Memory
    By Booie2k1 in forum C Programming
    Replies: 3
    Last Post: 03-11-2008, 06:09 AM
  4. Help with a problem regarding dynamic memory and arrays
    By Michty in forum C++ Programming
    Replies: 5
    Last Post: 07-26-2006, 01:26 PM
  5. shifting arrays
    By ZeroG in forum C Programming
    Replies: 6
    Last Post: 06-16-2004, 10:13 PM