Home > Net >  How do I shift all elements by 1 position after a certain index in an array? c#
How do I shift all elements by 1 position after a certain index in an array? c#

Time:04-28

starting array --> [1,2,3,4,5,6,7,8,null,null] desired array --> [1,2,3,null,4,5,6,7,8,null]

Basically trying to shift all the array elements after 3rd index by 1 position; this will just create a gap in the array.

How can I do this using a for loop?

CodePudding user response:

You can do this right rotation of elements in-place without creating an additional array.

The algorithm is something like this:

Store the last element, iterate backwards from the last position in the array, shift the elements by one and finally insert the last element at the third index:

int?[] arr = new int?[] { 1, 2, 3, 4, 5, 6, 7, 8, null, null };
const int StartIndex = 3;

int? last = arr[arr.Length - 1];
for (int i = arr.Length - 1; i > StartIndex; i--)
    arr[i] = arr[i - 1];
arr[StartIndex] = last;
  •  Tags:  
  • c#
  • Related