An example of an C language method that implements circular shifting of arrays
- 2020-06-19 11:10:11
- OfStack
algorithm
Reverse Array (array flip)
code
void reverse(int array[], int left, int right)
{
int l, r;
for (l = left, r = right; l < r; l++, r--)
{
array[l] = array[l] ^ array[r];
array[r] = array[l] ^ array[r]; // l ^ r ^ r = l ^ 0 = l.
array[l] = array[l] ^ array[r]; // l ^ r ^ l = r ^ 0 = r;
}
}
The above code realizes the exchange of variable values efficiently through xor operation, please remember:
Any number that is different from zero is itself. Any number that is different from 1 is negative.
Cyclic shift to the left
Assuming that we cyclically shift the n bit to the left, the steps are:
Flip the first n bit elements of the array; Flip the rest of the array; The array is then flipped and the n bit is rotated to the left.The order of the above steps can also be changed to step2 - > step1 - > step3.
code:
reverse(array, 0, left_shift_num - 1);
reverse(array, left_shift_num, array_size - 1);
reverse(array, 0, array_size - 1);
Cycle moves to the right
Assuming that we loop right shift the n bit, the steps are as follows:
Flip the post-ES39en bit element of the array; Flip the rest of the array; Flip the entire array, and you iterate over the n bit.The order of the above steps can also be changed to step2 - > step1 - > step3.
code:
reverse(array, 0, array_size - right_shift_num - 1);
reverse(array, array_size - right_shift_num, array_size - 1);
reverse(array, 0, array_size -1);