Jun 10, 2009

Given an array, right shift the array by cycle at the sh position Solution: Suppose the length of the array is n. Reverse all the elements from a[0]

Given an array, right shift the array by cycle at the sh position
Solution:
Suppose the length of the array is n. Reverse all the elements from a[0] to a[sh-1], reverse all the elements from a[sh] to a[n], reverse the whole array.
Refer to Programming Pearls: Column 2.3

foo(char* A, int sh)
{
reverse(A,0,sh-1);
reverse(A,sh,strlen(A));
reverse(A,0,strlen(A));
}

reverse(char* A,int min, int max)
{
for(int i=0;i<=(max-min)/2;i++)
{
char temp=A[min+i];
A[min+i]=A[max-i];
A[max-i]=temp;
}
}

No comments:

Post a Comment