I completed the schedule. I want to sort a given subset of vertices according to their degrees. So I wrote my own comparator with a name DegreeComparator.
private class DegreeComparator implements Comparator<Integer>
{
@Override
public int compare(Integer arg0, Integer arg1)
{
if(adj[arg1].size() == adj[arg0].size()) return arg1 - arg0;
else return adj[arg1].size() - adj[arg0].size());
}
}
So which of the following methods is more efficient?
Using TreeSet
public Collection<Integer> sort(Collection<Integer> unsorted)
{
Set<Integer> sorted = new TreeSet<Integer>(new DegreeComparator());
sorted.addAll(unsorted);
return sorted;
}
Using ArrayList
Collections.sort(unsorted, new DegreeComparator());
Please note that the second approach is not a function, but a single-line one.
Intuitively, I would prefer to choose the second. But I'm not sure if this is more efficient.
source
share