找到列表值时的列表进行排序的最佳方法列表、方法

2023-09-11 05:24:48 作者:娶了农村姑娘

让我们说我有一个Java的ArrayList,即排序。现在,我想找个值x的指数。什么是最快的(不超过30行code)的方式来做到这一点?使用的IndexOf()方法的?通过在for循环简单的所有值迭代?用一些很酷的算法?我们谈论的是围绕让我们说50整数键。

Let's say I have a Java ArrayList, that is sorted. Now I would like to find the index of value x. What would be the fastest (without more than 30 lines of code) way to do this? Use of the IndexOf() method? Iterate through all values in a simple for loop? Use of some cool algorithm? We are talking about around let's say 50 integer keys.

推荐答案

二进制搜索,但因为它是唯一50个项目,谁在乎(除非你有做千万次)?一个简单的线性搜索更简单,对50个项目在性能上的差异可以忽略不计。

Binary search, but since it's only 50 items, who cares (unless you have to do it millions of times)? A simple linear search is simpler and the difference in performance for 50 items is negligible.

修改:您还可以使用内置的java.util.Collections中的的binarySearch 方法。请注意,它会返回即使没有发现该项目的一个插入点。您可能需要做出额外​​的夫妇的检查,以确保该项目真的是你想要的。由于@Matthew为指针。

Edit: You could also use the built-in java.util.Collections binarySearch method. Be aware, that it will return an insertion point even if the item isn't found. You may need to make an extra couple of checks to make sure that the item really is the one you want. Thanks to @Matthew for the pointer.