A very efficient and economical way to shift an array

 How do you shift an array? For example, there is an array {a, b, c, d, 1, 2, 3, 4}, and the requirement is to cyclic-shift 3 elements to the right. That means, after the shift, the array looks like this: {2, 3, 4, a, b, c, d, 1}. This problem is so easy that most people can solve it in just one or two minutes, or even less time. However, here introduces another interesting way to shoot it, which uses reversing and is very economical in both time and space usage. The above example is used again to illustrate the whole process. Totally we need 2 times of reversing. The first time, we reverse the two subarrays with (n-k) and k elements respectively, that is {a, b, c, d, 1, 2, 3, 4} --> {1, d, c, b, a, 4, 3, 2}; the second time, we reverse the whole new array, that is {1, d, c, b, a, 4, 3, 2} --> {2, 3, 4, a, b, c, d, 1}. Job done. So interesting, efficient and economical, right? Below is one implementation.

  1. #include <iostream>
  2. using namespace std;
  3. template <typename T>
  4. void array_print(T* array, int n) {
  5.     for(int i = 0; i < n; ++i) {
  6.         cout << array[i] << " ";
  7.     }
  8.     cout << endl;
  9. }
  10. template <typename T>
  11. T* array_shift(T* array, int n, int k) {
  12.     k %= n;
  13.     if(k == 0) {
  14.         return array;
  15.     }
  16.     int temp;
  17.     // Reverse the left subarray with (n-k) elements.
  18.     for(int i = 0; i < (n-k)/2; ++i) {
  19.         temp = array[i];
  20.         array[i] = array[n-k-1-i];
  21.         array[n-k-1-i] = temp;
  22.     }
  23.     // Reverse the right subarray with k elements.
  24.     for(int i = 0; i < k/2; ++i) {
  25.         temp = array[(n-k)+i];
  26.         array[(n-k)+i] = array[(n-1)-i];
  27.         array[(n-1)-i] = temp;
  28.     }
  29.     // Reverse the whole array.
  30.     for(int i = 0; i < n/2; ++i) {
  31.         temp = array[i];
  32.         array[i] = array[n-1-i];
  33.         array[n-1-i] = temp;
  34.     }
  35.     return array;
  36. }
  37. int main() {
  38.     int ia[10] = {1,3,5,7,9,2,4,6,8,10};
  39.     array_print(array_shift(ia, 10, 7), 10);
  40.     char ca[8] = {'a','b','c','d','1','2','3','4'};
  41.     array_print(array_shift(ca, 8, 4), 8);
  42.     array_print(array_shift(ca, 8, 4), 8);
  43.     array_print(array_shift(ca, 8, 5), 8);
  44.     return 0;
  45. }

The command line prints:

7 9 2 4 6 8 10 1 3 5

1 2 3 4 a b c d

a b c d 1 2 3 4

d 1 2 3 4 a b c

 

Referenced to <Beauty of Programming>.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值