⌘BABAKOV.NET Let's code!
100% [light] [ru]

Rotating (Shifting) an Array K Times, Rotate Array K times C#

Example of rotating/shifting an array Array K times in C#

public static void Rotate(int[] nums, int k) {
        int len = nums.Length;
        int cnt = k%len;
        if ((len<2)||(cnt==0)){return;}
        int x = 0;
        int val = nums[x];
        int val_prev = nums[x];

            int x_start = x;
            for (int i = 0; i<len;i++)
            {
                x = x+cnt<len?x+cnt:(x+cnt)%len;
                val_prev = nums[x];
                nums[x] = val;

                if (x_start == x)
                {
                    x++;
                    val = nums[x];
                    x_start = x;
                }
                else
                {
                    val = val_prev;
                }
            }
    }

Meaning on example:
There is an array: [1,2,3,4,5]
We rotate it 3 times: K=3.
Result:
[3,4,5,1,2]

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.