开发者

C# shift two dimension array fast method

I have a 2D string array in C# and I need开发者_如何学Go to shift that array to left in one dimension how can I do that in efficient way

I dont want use nested for and i want an algurithm in O(n) not O(n2)

for (int i = 50; i < 300; i++)
{
    for (int j = 0; j < 300; j++)
    {
        numbers[i-50, j] = numbers[i, j];
    }
 }


If you want to shift large amounts of data around quickly, use Array.Copy rather than a loop that copies individual characters.

If you swap to a byte array and use Array.Copy or Buffer.BlockCopy you will probably improve the performance a bit more (but if you have to convert to/from character arrays you may lose everything you've gained).

(edit: Now that you've posted example code): If you use references to the array rows then you may be able to shift the references rather than having to move the data itself. Any you can still shift the references using Array.Copy)

But if you change your approach so you don't need to shift the data, you'll gain considerably better performance - not doing the work at all if you can avoid it is always faster! Chances are you can wrap the data in an accessor layer that keeps track of how much the data has been shifted and modifies your indexes to return the data you are after. (This will slightly slow down access to the data, but saves you shifting the data, so may result in a net win - depending on how much you access relative to how much you shift)


The most efficient way would be to not shift it at all, but instead change how you access the array. For example, keep an offset that tells you where in the dimension the first column is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜