将数字插入有序的arrayList中

时间:2012-10-14 21:36:45

标签: java

我有一个关于如何将任何数字插入有序ArrayList的有趣问题。让我们说用户输入[12,34,37,60,89];方法addListElement()应该遍历数组以找到新元素的索引。

用户输入数字50,新数组应为[12,34,37,50,60,89]。我使用for循环来遍历ArrayList,但我不确定我的if()语句。

public void addListElement() {
    System.out.println("Add number to arrayList");
    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();

    int loc = 0;
    for (int i = 0; i < aryList.size(); i++) {
        if (number > 0 && i < loc) {
            loc++;
        }
    }

    aryList.add(loc, number);
    System.out.println(aryList.toString());
}

6 个答案:

答案 0 :(得分:4)

试试这个:

int position = Collections.binarySearch(aryList, number);
aryList.add(position < 0 ? -position - 1 : position, number);

编辑感谢指出旧代码崩溃,如果该数字已经存在

答案 1 :(得分:2)

您可能希望使用List<E>.add(int idx, E element)方法。按顺序插入元素的想法是,对于某些数组 a ,元素 a i ,对于某些整数 n < / EM>:

a i &lt; = n&lt; = a i + 1 ,0&lt;我&lt; LEN(A)-1。

// edge case:  Size one list, number coming in is smaller.
if(aryList.size() == 1 && aryList.get(0) >= number) {
    aryList.add(0, number);
} else {
    for(int i = 0; i < aryList.size()-1; i++) {
        if(number >= aryList.get(i) && number <= aryList.get(i+1)) {
            aryList.add(i, number);
        }
    }
    // number is the largest seen; add it to the end.
    aryList.add(number);
}

答案 2 :(得分:1)

这也应该有用。由于列表已按升序排列,当您在列表中找到大于当前列表的数字时,请在arrayList中的此数字前插入新的第一个索引。

 for (int i = 0; i < aryList.size(); i++) {
    if (aryList.get(i)>number) {
       break;
    }
  loc++;
}

答案 3 :(得分:0)

int loc = 0;
int prevNumber = aryList.get(0);
for(int i = 1; i<aryList.size(); i++){
            if(number > prevNumber && number <= aryList.get(i)){ 
               return i;
            }
    prevNumber = aryList.get(i);
  }

答案 4 :(得分:0)

只要有更多元素且数量小于当前元素,就增加索引。当用户提供的数字大于列表中当前的任何数字时,您还必须检查i!= list.size()。

while (number >= 0 && number <= list.get(i) && i < list.size()) {
    i++;
}

list.add(i, number);

答案 5 :(得分:0)

我认为你的元素是按上升顺序排序的

 public void insert(int x){
        // loop through all elements
        for (int i = 0; i < arrayList.size(); i++) {
            // if the element you are looking at is smaller than x, 
            // go to the next element
            if (arrayList.get(i) < x) continue;
            // if the element equals x, return, because we don't add duplicates
            if (arrayList.get(i) == x) return;
            // otherwise, we have found the location to add x
            arrayList.add(i, x);
            return;
        }
        // we looked through all of the elements, and they were all
        // smaller than x, so we add x to the end of the list
        arrayList.add(x);
    }

如果要在ArrayList中插入重复项,只需删除代码行

即可
if (arrayList.get(i) == x) return;