您的位置:首页 > 其它

A very efficient and economical way to shift an array

2008-12-01 13:02 399 查看
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.

#include <iostream>

using namespace std;

template <typename T>

void array_print(T* array, int n) {

for(int i = 0; i < n; ++i) {

cout << array[i] << " ";

}

cout << endl;

}

template <typename T>

T* array_shift(T* array, int n, int k) {

k %= n;

if(k == 0) {

return array;

}

int temp;

// Reverse the left subarray with (n-k) elements.

for(int i = 0; i < (n-k)/2; ++i) {

temp = array[i];

array[i] = array[n-k-1-i];

array[n-k-1-i] = temp;

}

// Reverse the right subarray with k elements.

for(int i = 0; i < k/2; ++i) {

temp = array[(n-k)+i];

array[(n-k)+i] = array[(n-1)-i];

array[(n-1)-i] = temp;

}

// Reverse the whole array.

for(int i = 0; i < n/2; ++i) {

temp = array[i];

array[i] = array[n-1-i];

array[n-1-i] = temp;

}

return array;

}

int main() {

int ia[10] = {1,3,5,7,9,2,4,6,8,10};

array_print(array_shift(ia, 10, 7), 10);

char ca[8] = {'a','b','c','d','1','2','3','4'};

array_print(array_shift(ca, 8, 4), 8);

array_print(array_shift(ca, 8, 4), 8);

array_print(array_shift(ca, 8, 5), 8);

return 0;

}

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>.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐