简体   繁体   中英

I have a list of integers , how to sort it?

Have a list of integers like

List<Integer> l = new ArrayList<Integer>();

I think calling l.contains is slow, how to sort the list. After sorting, will l.contains behave faster?

Is there any sortedList I can use directly?

它不能比这更简单。

Collections.sort(l);

Sorting of list would not make contains operation faster. It still be O(n) in worst case.

However you can sort your list and perform the binary search on top of it.

Collections.sort(l);
Collections.binarySearch(l, a);

This will take O(lg(n)) time in worst case.

But if you want a high performance contains operation consider using HashSet instead of ArrayList . It takes nearly constant time.

你可以使用Collections.sort(l);

Collections中sort()方法可以帮助您对ArrayList进行排序。

contains() on a ArrayList doesn't assume the array is sorted, even if it is. You'll want to use some sort of set (HashSet will give you the best find performance, and a LinkedHashSet will retain the order. Even a TreeList will give you better performance.)

TreeSet可能对您有用。

SortedSet<Integer> s = new TreeSet<Integer>(l);

If Collections.sort(l) does not give the desired result, try Collections.sort(l, comparator) where "comparator" is something like this:

class MyComparator implements Comparator<Integer>
{
  public int compare(Integer lhs, Integer rhs)
  {
    // perform the desired comparison.
  }
}

Edit: I'll leave this up, but the answer by "Mairbek Khadikov" seems to be the best answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM