简体   繁体   English

如何在数组中的某个索引后将所有元素移动 1 position? c#

[英]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]起始数组 --> [1,2,3,4,5,6,7,8,null,null] 所需数组 --> [1,2,3,null,4,5,6,7,8,无效的]

Basically trying to shift all the array elements after 3rd index by 1 position;基本上尝试将第 3 个索引之后的所有数组元素移动 1 position; this will just create a gap in the array.这只会在数组中造成一个缺口。

How can I do this using a for loop?如何使用 for 循环执行此操作?

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:存储最后一个元素,从数组中最后一个 position 向后迭代,将元素移动一位,最后在第三个索引处插入最后一个元素:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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