开发者

Sorting a List of Locations

I want to sort a list of android.location.Location. The sort should base on the di开发者_JAVA技巧stance of my location to the location from the list. So i think the distance should be calculated during the search process. And so I've decided to use insert sort.

Is this the right choice?

Thanks a lot


If it's a List of locations, I'd go with Collections.sort + a custom Comparator:

final Location myLocation = someLocation;

Collections.sort(locations, new Comparator<Location>() {
    @Override
    public int compare(Location o1, Location o2) {
        Float dist1 = o1.distanceTo(myLocation);
        Float dist2 = o2.distanceTo(myLocation);
        return dist1.compareTo(dist2);
    }
});


If you have a lot of locations in your list, you may want to think about the time complexity of the sorting algorithm.

Insertion Sort has the Worst Case Senario time complexity of O(n^2) [n is the number of items in the list] meaning if the list to sort was a reversed sorted list it would have to traverse through the entire list for every object in the list in order to sort it. This may not seem like a problem unless you have very large lists.

if you aren't going to be having extremely large lists to sort through, insertion sort can work fine for your situation. Some other sorts you could look into include Selection Sort, Bubble Sort, Quick Sort or Merge Sort.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜