Thursday, July 30, 2009

Can someone help with this C++ Question?

Write a C++ function void ShiftRight (int A[], int m, int n) to shift all elements in the array A to the right m places. Array A has n elements. For instance, if ARY array has {1,2,3,4,5}, calling ShiftRight(ARY, 2, 5) will change the contents of ARY to {4,5,1,2,3}.

Can someone help with this C++ Question?
This syntax is java. But the algorithm is correct.





static void ShiftRight ( int A[], int m, int n )


{


int B[] = new int[n]; // Temp Array


for ( int x = 0; x %26lt; A.length; x++ )


{


int y = ( (x+m)%n );


B[y] = A[x];


// You will need to copy the temp array and set it to your original.


}
Reply:Hello. It's been a little while since I've used C++, so my syntax is rusty, but here's the basic idea:





void ShiftRight(int A[], int m, int n) {


int temp;


for (int i = 0; i %26lt; m; i++) { // Each loop is one shift right.


temp = A[n];


for (int j = n-1; j %26gt; 0; j--) { // Starting at the right, each entry in the array will become the one before it. This is the shift.


A[ j ] = A[ j-1 ];


}


A[0] = temp; // temp was used to place the last entry at the beginning of the array.


}


}





I hope this helps! :)


No comments:

Post a Comment