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; }



LinkBack URL
About LinkBacks



