gpt4 book ai didi

java - 当值输入到数组中时对数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:31 25 4
gpt4 key购买 nike

我需要一个循环的帮助,如果新添加的值低于现有值,该循环将移动数组的元素,以便在输入新值时对数组进行排序。

数组一开始是空的。

我尝试了几个循环,但它们在我的情况下似乎不起作用,因为它们是用于已经满的数组的循环。

这是我目前拥有的代码。

if(index < 0)
index = -(index + 1);

if(arr[index] > key)
for(int i = 0; i < count -1; i++) {
arr[index + i] = arr[index + i + 1];
}

arr[index] = key;

索引来自二分查找。

例如,如果我先输入 80,它将占用 arr[0] 的位置。然后我输入 45,它也将占用 arr[0] 的插槽。

因为45,key,比现有的arr[0](80)小,所以80是向上移动一个索引。

最佳答案

您可能希望循环执行以下操作:

  1. 移动具有索引的元素 > index 以便为新元素腾出空间,并且
  2. 然后将元素添加到给定索引。
for (int  i = count; i > index; i--) {
arr[i] = arr[i - 1]; // shifts the elements to the one place right
}
arr[index] = key; // add the key to the given index

注意:count为当前数组元素个数,小于arr.length

关于java - 当值输入到数组中时对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820739/

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