c# - C# 中的快速数组移位实现?

标签 c# algorithm optimization

我需要将数组向右和向左移动 N 个位置。

从我移动到的一侧弹出的项目必须在另一侧返回。

右移 13:

[0,1,2,3,4,5,6,7,8,9] -> [7,8,9,0,1,2,3,4,5,6]

左移 15:

[0,1,2,3,4,5,6,7,8,9] -> [5,6,7,8,9,0,1,2,3,4]

此操作将发生数百万次并且必须非常快。

我当前的实现如下。请查看并建议是否需要进行一些优化。

if (shift > 0)
{
    int offset = array.Length % shift;
    if (offset > 0)
    {
        byte[] temp = new byte[offset];
        if (!right)
        {
            Array.Copy(array, temp, offset);
            Array.Copy(array, offset, array, 0, array.Length - offset);
            Array.Copy(temp, 0, array, array.Length - offset, temp.Length);
        }
        else
        {
            Array.Copy(array, array.Length - offset, temp, 0, offset);
            Array.Copy(array, 0, array, offset, array.Length - offset);
            Array.Copy(temp, 0, array, 0, temp.Length);
        }
    }
}

关于它会移动多少的提示(但我怀疑它会导致优化):

-  depends on the entropy of the array itself
-  for aray that are full of same values it will get shifted roughtly 0
-  more entropy means higher shift value
-  direction of shift will be used generally more to the left

附言。无法获得运行不安全代码的安全权限:/

PS2:生成的数组必须作为数组传递给不同的库进行进一步处理,所以我不能只是换行和重新索引。

PS3:我更愿意在同一个数组上工作,因为该方法使用 ref,并且在一个新数组上执行此操作然后再复制回去会很耗时(我正在使用 '由于移动而脱落的部分的 temp' 数组)。

最佳答案

你应该使用 Buffer.BlockCopy反而。它绕过数组索引并执行快速内存复制。请记住,BlockCopy 以字节为单位复制数据,而不是根据数组元素的大小,因此请确保使用 sizeof() 来说明这一点。

关于c# - C# 中的快速数组移位实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6602559/

相关文章:

c# - 我收到此错误消息 : Access denied for user (Using password YES)

python - 快速替换字符串中的字符并检查子字符串是否是回文

python - 具有 GPU 支持的 Levenberg-Marquardt 算法

c# - .NET4.0 SqlConnectionStringBuilder 缺少 ApplicationIntent 和 MultiSubnetFailover 属性

c# - wpf c# backgroundworker 等到完成

algorithm - (facebook like app) show post algorithm design

C++ 排序类比 qsort 更快

haskell - 如何强制 GHC 仅计算静态表达式一次

c# - 有人能告诉我我的 log4net 配置/实现有什么问题吗?

algorithm - 在 Fortran 中重新启动循环