算法 - 圆形阵列旋转

Algorithms - Circular Array Rotation

本文关键字:阵列 旋转 算法      更新时间:2023-10-16

圆形阵列旋转的线性复杂性实现是否正确?

n =元素数量k =旋转数

    int write_to     = 0;
    int copy_current = 0;
    int copy_final   = a[0];
    int rotation     = k;
    int position     = 0;
    for (int i = 0; i < n; i++) {
        write_to     = (position + rotation) % n;
        copy_current = a[write_to];
        a[write_to]  = copy_final;
        position     = write_to;
        copy_final   = copy_current;
     }

no。

考虑此示例。

#include <iostream>
int main(void) {
    int n = 6;
    int k = 2;
    int a[] = {1, 2, 3, 4, 5, 6};
    int write_to     = 0;
    int copy_current = 0;
    int copy_final   = a[0];
    int rotation     = k;
    int position     = 0;
    for (int i = 0; i < n; i++) {
        write_to     = (position + rotation) % n;
        copy_current = a[write_to];
        a[write_to]  = copy_final;
        position     = write_to;
        copy_final   = copy_current;
     }
    for (int i = 0; i < n; i++) {
        std::cout << a[i] << (i + 1 < n ? ' ' : 'n');
    }
    return 0;
}

预期结果:

5 6 1 2 3 4

实际结果:

3 2 1 4 1 6

使用stl ::在std :: array上旋转,您可以旋转,例如2,as:

std::array<int, 6> a{1, 2, 3, 4, 5, 6};
std::rotate(begin(a), begin(a) + 2, end(a)); // left rotate by 2

屈服:3 4 5 6 1 2,或右键,例如2,为:

std::rotate(begin(a), end(a) - 2, end(a)); // right rotate by 2

屈服:5 6 1 2 3 4,具有线性复杂性。

leftright方向上旋转n的长度CC_1的数组。

代码在Java中

我定义了一个方向枚举:

public enum Direction {
    L, R
};

timesdirection旋转:

public static final void rotate(int[] arr, int times, Direction direction) {
    if (arr == null || times < 0) {
        throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
    }
    int offset = arr.length - times % arr.length;
    if (offset > 0) {
        int[] copy = arr.clone();
        for (int i = 0; i < arr.length; ++i) {
            int j = (i + offset) % arr.length;
            if (Direction.R.equals(direction)) {
                arr[i] = copy[j];
            } else {
                arr[j] = copy[i];
            }
        }
    }
}

复杂性:o(n)。

示例:输入:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]旋转3left输出:[4, 5, 6, 7, 8, 9, 10, 1, 2, 3]

输入:[4, 5, 6, 7, 8, 9, 10, 1, 2, 3]旋转3right输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]