Article Directory
foreword
This article uses C language to realize the rotation of the array (right rotation)
1. Array rotation
1. Effect
If there is an array value: 1 2 3 4 5, then its rotation effect is:
2. Code
//数组旋转
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10
//旋转数组
void rotate(int arr[], int sz, int n) //两个临时变量
{
for (int i = 0; i < n%sz; i++)//旋转次数
{
int a = arr[sz - 1];
for (int j = 0; j < sz; j++)
{
int temp = arr[j];
arr[j] = a;
a = temp;
}
}
}
//随机初始化数组
void Initarr(int arr[],int a)
{
srand((unsigned)time(NULL));
printf("随机初始化数组共%d个数(范围是0~100).\n", a);
for (int i = 0; i < a; i++)
{
arr[i] = rand() % 100;
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int n = 0;
int arr[N];
Initarr(arr,N);
printf("请输入要旋转的次数:\n");
scanf_s("%d", &n);//VS编译器scanf——>scanf_s
rotate(arr, N,n);
printf("旋转结果:\n");
for (int j = 0; j <N; ++j)
{
printf("%d ", arr[j]);
}
return 0;
}
3. Running results
2. Process analysis
1. Randomly read data
2. Array rotation
Summarize
That's all for this article.