使一维数组各元素向左,右循环移动m个位置c代码
时间: 2024-03-23 09:39:50 浏览: 38
以下是将数组向左循环移动m个位置的C语言代码实现:
```c
void rotateLeft(int arr[], int n, int m) {
// step 1: reverse the first m elements
for (int i = 0; i < m / 2; i++) {
int temp = arr[i];
arr[i] = arr[m - 1 - i];
arr[m - 1 - i] = temp;
}
// step 2: reverse the remaining n-m elements
for (int i = m; i < (m + n) / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i + m];
arr[n - 1 - i + m] = temp;
}
// step 3: reverse the whole array
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
```
以下是将数组向右循环移动m个位置的C语言代码实现:
```c
void rotateRight(int arr[], int n, int m) {
// step 1: reverse the last m elements
for (int i = n - m; i < (n - m + m / 2); i++) {
int temp = arr[i];
arr[i] = arr[2 * (n - m) + m - 1 - i];
arr[2 * (n - m) + m - 1 - i] = temp;
}
// step 2: reverse the remaining n-m elements
for (int i = 0; i < (n - m) / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
// step 3: reverse the whole array
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
```
这两个函数都接受三个参数,第一个参数是要操作的数组,第二个参数是数组的长度,第三个参数是要移动的位置数。注意,这两个函数都是对原数组进行修改,不返回任何值。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)