Java根据元素编号重新排列数组

标签 java arrays for-loop

这是我的数组:

int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

假设我想将 myArray[3](它可以是任何元素)和 myArray[6](与这个相同)移动到数组的前面,同时重新排列后面,我该怎么做?示例:

这个:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

进入这个:

{3, 6, 0, 1, 2, 4, 5, 7, 8, 9}

最佳答案

要将索引 x 移到前面,您需要:

  • 记住索引 x 的内容
  • 复制从 0x - 1 的所有内容向上一个索引,例如使用 System.arrayCopy
  • 将索引 0 处的值设置为您在第一步中记住的值

例如:

public void moveToHead(int[] values, int index)
{
    // TODO: Argument validation
    int value = values[index];
    System.arraycopy(values, 0, values, 1, index - 1);
    values[0] = value;
}

请注意 System.arraycopy 适本地处理复制:

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

您的原始示例提到了两个元素 - 虽然您可以提前知道这两个元素,但可以更有效地完成所有这些操作,将其建模为两个 moveToHead< 会简单得多 调用。您需要注意顺序 - 例如,如果您想先将索引 6 移动到头部,则需要移动索引 4 而不是索引 3,以考虑到第一步。

关于Java根据元素编号重新排列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572038/

相关文章:

python - 如何从嵌套在另一个列表中的列表中的列表中提取但将项目保存在一起

java - 如何让 Java MANIFEST.MF 包含 Maven 版本号

java - 在 NetBeans 中动态更改小部件的图标

javascript - javascript 项目和数组的问题(下雨)

python - 添加列数据框 python plus 乘以数组中的数字

python - 在python中按数字顺序打印输出

java - 关于 REST 响应和 XMLElement

java - 如何控制日志文件的大小?

c++ - 运行时错误问题

java - 从我的用户/主类控制链表队列,不起作用