The rotation of multi-dimensional arrays, or tensors, is a fundamental operation in computer science with applications ranging from data processing to scientific computing. While various methods exist, achieving this rotation in-place (i.e., with O(1) auxiliary space) presents a significant algorithmic challenge. The elegant three-reversal algorithm provides a well-known O(1) space solution for one-dimensional arrays. This paper introduces a generalization of this method to N dimensions, resulting in the "$2^n+1$ reversal algorithm". This algorithm achieves in-place tensor rotation with O(1) auxiliary space and a time complexity linear in the number of elements. We provide a formal definition for N-dimensional tensor reversal, present the algorithm with detailed pseudocode, and offer a rigorous proof of its correctness, demonstrating that the pattern observed in one dimension ($2^1+1=3$ reversals) and two dimensions ($2^2+1=5$ reversals) holds for any arbitrary number of dimensions.
翻译:多维数组(即张量)的旋转是计算机科学中的基本操作,其应用范围涵盖数据处理到科学计算。尽管存在多种方法,但实现原地旋转(即仅使用O(1)辅助空间)仍是一个重要的算法挑战。优雅的三次反转算法为一维数组提供了众所周知的O(1)空间解决方案。本文将该方法推广至N维,提出了“$2^n+1$次反转算法”。该算法以O(1)辅助空间实现张量的原地旋转,时间复杂度与元素数量呈线性关系。我们给出了N维张量反转的形式化定义,提供了包含详细伪代码的算法描述,并给出了其正确性的严格证明,表明在一维($2^1+1=3$次反转)和二维($2^2+1=5$次反转)中观察到的模式适用于任意维度。