赞
踩
数组向右旋转的四种方法:
在这里向右移动三位位例
1,基本方法向右移动一次然后循环
2,开辟一个新的空间
3,交换三次
4,从第k位打印(并不能改变数组内容的真实顺序)
#include<stdio.h> #include<assert.h> #include<stdlib.h> #include"Seqlist.h" void Show_arr(int *a,int n) { assert(a!=nullptr); for (int i = 0; i < n; i++) { printf("%d ",a[i]); } printf("\n"); } void Mov(int* a,int n) { assert(a != nullptr); int b = a[0]; int i = n - 1; for(i;i>0;i--) { a[(i + 1) % n] = a[i]; } a[1] = b; } void Rev1(int *a,int k,int n) { assert(a != nullptr); k = k%n; for (int i = 0; i < k; i++) { Mov(a, n); } } void Rev2(int *a,int k,int n) { assert(a != nullptr); int* b =(int*) malloc(sizeof(int)*n); k = k % n; int j =k; for (int i = 0; i < n-k; i++) { b[j] = a[i]; j++; } j = 0; for (int i = n - k; i < n; i++) { b[j] = a[i]; j++; } for (int i = 0; i < n; i++) { a[i] = b[i]; } free(b); b = nullptr; } void Swap(int* a, int left, int right) { while (left<right) { int p = a[left]; a[left] = a[right]; a[right] = p; left++; right--; } } void Rev3(int* a, int k, int n) { assert(a!=nullptr); k = k % n; Swap(a,0,n-k-1); Swap(a,n-k,n-1); Swap(a,0,n-1); } void Rev4(int* a, int k, int n) { assert(a!=nullptr); k = k % n; int j = n - k; int i=0; while (i<n) { printf("%d ",a[j]); j= (j+ 1) % n; i++; } printf("\n"); } int main() { int arr[] = { 1,2,3,4,5,6,7 }; int n = sizeof(arr) / sizeof(arr[0]); //Rev1(arr, 3, n); /*Rev2(arr, 3,n);*/ /*Rev3(arr, 3, n);*/ Rev4(arr, 3, n); //Show_arr(arr, n); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。