简体   繁体   中英

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

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM