Hello everyone. I am having hard times in dealing with this problem which I've been given. It simply asks me to shift an array K positions without using additional memory. I cannot ask them what they mean by that. No memory, like... not even using a temporary variable for the loop?!
Here is an example:
1 2 3 4 5 6 7 8 shifted 3 times to the right gives:
4 5 6 7 8 1 2 3
Of course, the array is not sorted necesarray, that was just an example.
#include <iostream>
using namespace std;
void shiftArray(int numbers[], int sizeofArray, int k)
{
int index;
for(index = 0; index < sizeofArray; index++)
{
if(index >= sizeofArray - k)
{
numbers[index] = numbers[index % (sizeofArray - index)];
}
else
{
numbers[index] = numbers[index + k];
}
}
}
int main(int argc,char* argv)
{
int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8};
int k = 3;
int sizeofArray = 8;
shiftArray(numbers, sizeofArray, k);
int i;
for(i = 0; i < sizeofArray; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
This is my code so far. I know I used a temporary variable for the size, but that was because I cannot do it with sizeof...
Also, the problem is that after updating the first sizeofArray - k numbers, the last k numbers will be updated with the replaced values and not with the original ones... can someone please tell me how should I correct it? Or at least give me another way of looking at the problem? Thanks for your time.