数组元素循环右移
include<stdio.h> #include<process.h> #pragma warning(disable:4996) #include"gcd.h" #include"Reverse.h" void ShiftRight1(int m,int *a,int n) { int _i; int k; int nxt; int tmp; if (m == 0) return; if (n >= m) _i = gcd(n, m); else _i = gcd(m, n); for (int i = 0; i < _i; i++) { k = i; //该轮跳写起始i nxt = a[k]; //待跳写元素 do { k = (k + m) % n; tmp = a[k]; //写入原位前暂存该位元素 a[k] = nxt; nxt = tmp; } while (k != i); } } void ShiftRight2(int m,int *a,int n) { m %= n; //m置为有效的移位数量 if (m == 0)return; Reverse(a, n); //数组逆序 Reverse(a, m); //以右循环移位数为分割,前后分别逆序 Reverse(a + m, n - m); } int main() { int n; int M; int *a; int _i; scanf("%d %d", &n, &M); a = new int[n]; for (int i = 0; i<n; i++) { scanf("%d", &a[i]); } //ShiftRight1(M, a, n); ShiftRight2(M, a, n); for (int i = 0; i<n; i++) { printf("%d ", a[i]); } printf("\n"); system("pause"); }