我怎么能循环移位而无需额外的堆内存中的数组? [英] How can I cyclically shift an array without additional heap memory?

查看:90
本文介绍了我怎么能循环移位而无需额外的堆内存中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何写一个函数移(INT *改编,INT K)循环移位数组的一些整数k?我不能说从堆中的malloc的记忆。

How can I write a function shift(int* arr, int k) cyclically shift an array by some integer k? I cannot say "malloc" memory from the heap.

例如,使用伪code,位移(1,2,3,4],2)返回 [3, 4,1,2] 位移(3,1,5,5],103)返回 [ 1,5,5,3] 。我已经使用模量达到这种效果尝试,如本Java程序,在此我基本上完成了一半的数组和交换价值的循环。

For instance, using pseudocode, shift([1, 2, 3, 4], 2) returns [3, 4, 1, 2], and shift([3, 1, 5, 5], 103) returns [1, 5, 5, 3]. I have tried using modulus to achieve this effect, as shown in this Java program, in which I basically iterate through half of the array and swap values.

public static int* shift(int* arr, int k) {
  int half_array_len = arr.length / 2;
  for (int i = 0; i < half_array_len; ++i) {
    // Swap!
    int newIndex = (i + k) % arr.length;
    int temp = arr[i];
    arr[i] = arr[newIndex];
    arr[newIndex] = arr[i];
  }
  return arr;
}

不过,我相信,这个功能仅适用于偶数lengthed阵列。

However, I believe that this function only works for even-lengthed arrays.

我如何实现任意长度的数组?答案可以在任何你想要的语言(Java,C ++, OOK OOK!,等)。

How can I implement shift for arrays of any length? Answers can be in any language you want (Java, C++, Ook Ook!, etc.).

推荐答案

(已经被问了几次了。)基本上有三种典型的就地算法致力于解决这个问题的描述和奔特力的编程珠玑分析(杂耍,逆转和块交换算法)。这些幻灯片描述了他们足够的细节

(Has been asked several times before.) Basically, three classic in-place algorithms dedicated to solving this problem are described and analyzed in Bentley's "Programming Pearls" (Juggling, Reversal and Block Swap algorithms). These slides describe them in sufficient detail

HTTP://www.cs.bell-labs。 COM /厘米/ CS /珍珠/ s02b.pdf

最简单的算法是反转算法。简单地扭转整个数组,然后反向每个[N - k]和[K]块独立。完成。 (从哪个结束[k]的块进行计数依赖于移动的方向。)

The simplest algorithm is the Reversal Algorithm. Simply reverse the entire array and then reverse each [n - k] and [k] block independently. Done. (From which end the [k] block is counted depends on the direction of the shift.)

当然,是有意义的首先规格化 K,即做 K = K%N 来确保 K 小于 N

Of course, it makes sense to normalize the k first, i.e, do k = k % n to make sure k is less than n.

P.S。在C ++中的答案是使用的std ::旋转,这不正是你想要的东西。但我怀疑这是你寻求答案。虽然你可能想看看的一些实施的std ::旋转(如果只是为了发现他们通常使用冲销算法:)

P.S. In C++ the answer would be to use std::rotate, which does exactly what you want. But I doubt this is the answer you seek. Although you might want to take a look at some implementations of std::rotate (if only to discover that they typically use the Reversal algorithm :)

这篇关于我怎么能循环移位而无需额外的堆内存中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆