I am trying to implement left array rotation using the method described here: http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf (under section Reversal algorithm)
I am having trouble reversing the array when the start index isn’t 0.
Here is what I have so far:
void reverse_arr(int *a, int start, int end)
{
int i;
int len = end - start;
//printf("Len pre loop: %d\n", len);
int swap;
for(i = start; i < --len; i++)
{
//printf("start: %d\tlen: %d\n", start, len);
swap = a[i];
a[i] = a[len];
a[len] = swap;
}
}
This works great when the start index is 0, but when it is anything else it never reverses all of the elements.
ex:
int test[] = {1,2,3,4,5,6};
reverse_arr(test, 0, 2); //reverse the first 2 elements of the array
results in: {2,1,3,4,5,6} which is expected
int test[] = {1,2,3,4,5,6};
reverse_arr(test, 2, 6); //reverse the last 4 elements of the array
results in: {2,1,4,3,5,6} which is not expected, only the 3 and 4 were reversed.
Any help would be appreciated.
You need to adjust the other subscript in the swap:
You could probably also use:
Working test code
And the results from compiling with -DVERSION1 or not are the same: