温馨提示×

c语言数组循环右移怎么实现

小亿
97
2024-07-26 22:48:12
栏目: 编程语言

要实现c语言数组的循环右移,可以通过以下步骤实现:

  1. 确定右移的位数,假设为n。
  2. 创建一个临时数组,将原数组的后n个元素复制到临时数组中。
  3. 将原数组的前面部分向后移动n个位置,空出的位置补0。
  4. 将临时数组中的元素复制到原数组中。

以下是一个示例代码:

#include <stdio.h>

void rightRotate(int arr[], int n, int shift) {
    int temp[shift];
    // 将后shift个元素复制到临时数组中
    for (int i = 0; i < shift; i++) {
        temp[i] = arr[n - shift + i];
    }
    // 将前面的元素向后移动shift个位置
    for (int i = n - 1; i >= shift; i--) {
        arr[i] = arr[i - shift];
    }
    // 将临时数组中的元素复制到原数组中
    for (int i = 0; i < shift; i++) {
        arr[i] = temp[i];
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int shift = 2;
    
    rightRotate(arr, n, shift);
    
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

以上代码实现了一个将数组循环右移的功能,并输出移动后的结果。

0