Keep ArrayList sorted after every add call by finding index to add Integer very quickly (1 million add calls needed)

huangapple go评论74阅读模式
英文:

Keep ArrayList sorted after every add call by finding index to add Integer very quickly (1 million add calls needed)

问题

老师要求我逐个将一个整数项添加到MySortedArray类内部的泛型ArrayList中。我必须添加1,000,000个项目。他希望我在MySortedArray中实现的自定义add方法在每次添加后都能对ArrayList进行排序。然而,在每次add()调用后进行一百万次排序太慢了。我应该怎么做?我需要能够快速找到应该在ArrayList中添加整数项的索引。二分搜索是否可行?

@Test
void testRandomInts() {
    MySortedArray<Integer> ints = new MySortedArray<>(10);
    
    for (int i = 0; i < 200; i++) {
        int num = (int)(Math.random() * 10 + 1);
        ints.add(num);
    }
    System.out.println("array is: " + ints.contents.toString());
    assertTrue(isSorted(ints));
}
英文:

My teacher wants me to add an Integer item one at a time to a generic arraylist inside MySortedArray Class. I have to add 1_000_000 items. The custom add method he wants me to implement in MySortedArray, needs to add able to sort the arraylist after every addition. However, sorting it a million times after every add() call is too slow. What am I supposed to do? I need to be able to find the index in the ArrayList where I should add the Integer item very quickly. Would binary search work?

    @Test
	void testRandomInts() {
		MySortedArray&lt;Integer&gt; ints = new MySortedArray&lt;&gt;(10);
		
		for (int i = 0; i &lt; 200; i++) {
			int num = (int)(Math.random() * 10 + 1);
			ints.add(num);
		}
		System.out.println(&quot;array is: &quot; + ints.contents.toString());
		assertTrue(isSorted(ints));
	}

答案1

得分: 0

int index = Collections.binarySearch(contents, item);
if (index < 0) index = ~index;
contents.add(index, item);
英文:
  int index = Collections.binarySearch(contents, item);
  if (index &lt; 0) index = ~index;
  contents.add(index, item);

huangapple
  • 本文由 发表于 2020年10月5日 04:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64199619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定