On Monday, 3 October 2022 at 18:09:05 UTC, Fausto wrote:
Hello all,
I am trying to rotate left an array.
I found a very basic way, and I am not sure if there is
something clever than this :) maybe using slices...
Here we can't use slice assignment instead of the inner loop
because that doesn't work for an overlapping slice. (Instead
there's `copy` in std.algorithm).
The algorithm you wrote doesn't scale the best for speed - yours
is the second one mentioned here:
https://www.geeksforgeeks.org/array-rotation/
Phobos has `bringToFront(arr[0..2], arr[2..$])` which does the
same thing as a `rotate(arr, 2)` function. It seems to use the
third algorithm from the link (or at least has the same time and
space complexity).
The first algorithm may also work better in some cases, when
swapping is expensive or when the result is duplicated anyway.