gpt4 book ai didi

C# 将数组的元素移动到特定点,并将特定元素拉到前面

转载 作者:行者123 更新时间:2023-11-30 14:23:34 28 4
gpt4 key购买 nike

我的问题是我想在数组中有一个特定的元素,将它复制到另一个变量,将整个数组右移到那个元素,然后把这个元素放在前面。在漂亮的绘图中,它看起来像这样。

[0, 1, 2, 3, 4, 5]
^

[0, 1, 2, null, 4, 5]
^ (3)

[null, 0, 1, 2, 4, 5]
^ (3)

[null, 0, 1, 2, 4, 5]
^ (3)

[3, 0, 1, 2, 4, 5]
^

我已经尝试使用 for 循环将元素放在前面,然后插入 3,但我担心我的方法不是最有效或最快的方法。

这是我尝试过的。

        int elementAt = 3;
int[] array = { 0, 1, 2, 3, 4, 5 };
int mem = array[elementAt];
for (int i = elementAt; i > 0; i--)
array[i] = array[i - 1];
array[0] = mem;

我怀疑像 Array.Copy 这样的东西可以做得更快......?

编辑:下面的每个答案在特定情况下都有自己的用途。这个问题没有确定的答案,让这些结果让你选择使用哪种方法。

iterations, index, arraysize
HIGH, HIGH, HIGH
Speed for ShiftRightAt: 6616, ticks: 28007912
Speed for shiftlist: 3556, ticks: 15054635
Speed for arrayCopy: 1742, ticks: 7376152
Speed for MoveValueToFront: 67, ticks: 285901
LOW, LOW, HIGH
Speed for ShiftRightAt: 0, ticks: 28
Speed for shiftlist: 42, ticks: 180476
Speed for arrayCopy: 33, ticks: 142717
Speed for MoveValueToFront: 0, ticks: 67
HIGH, LOW, HIGH
Speed for ShiftRightAt: 0, ticks: 1399
Speed for shiftlist: 3624, ticks: 15341777
Speed for arrayCopy: 3177, ticks: 13449012
Speed for MoveValueToFront: 0, ticks: 926
LOW, HIGH, HIGH
Speed for ShiftRightAt: 73, ticks: 311428
Speed for shiftlist: 41, ticks: 174652
Speed for arrayCopy: 18, ticks: 79768
Speed for MoveValueToFront: 65, ticks: 277266
HIGH, HIGH, LOW
Speed for ShiftRightAt: 0, ticks: 1379
Speed for shiftlist: 0, ticks: 3902
Speed for arrayCopy: 0, ticks: 728
Speed for MoveValueToFront: 0, ticks: 914
LOW, LOW, LOW
Speed for ShiftRightAt: 0, ticks: 3
Speed for shiftlist: 0, ticks: 32
Speed for arrayCopy: 0, ticks: 11
Speed for MoveValueToFront: 0, ticks: 12
HIGH, LOW, LOW
Speed for ShiftRightAt: 0, ticks: 135
Speed for shiftlist: 0, ticks: 3850
Speed for arrayCopy: 0, ticks: 998
Speed for MoveValueToFront: 0, ticks: 840
LOW, HIGH, LOW
Speed for ShiftRightAt: 0, ticks: 15
Speed for shiftlist: 0, ticks: 16
Speed for arrayCopy: 0, ticks: 9
Speed for MoveValueToFront: 0, ticks: 39

测试方法: https://pastebin.com/HKkixHGR

最佳答案

你的漂亮图画正好给出了你需要写的东西。

public static void ShiftRightAt<T>(T[] array, int index)
{
if (index < 0 || index >= array.Length) return; // throw exception

var element = array[index]; // take out the element

for (int i = index; i > 0; i--)
{
array[i] = array[i - 1];
}

array[0] = element;
}

关于C# 将数组的元素移动到特定点,并将特定元素拉到前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783661/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com