Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an ArrayList or a LinkedList better for sorting?

I want to use data structure that needs to be sorted every now and again. The size of the data structure will hardly exceed 1000 items.

Which one is better - ArrayList or LinkedList?

Which sorting algorithm is better to use?

like image 239
Sergey Gazaryan Avatar asked Nov 09 '11 17:11

Sergey Gazaryan


People also ask

Why we use ArrayList instead of LinkedList?

ArrayList provides constant time for search operation, so it is better to use ArrayList if searching is more frequent operation than add and remove operation. The LinkedList provides constant time for add and remove operations. So it is better to use LinkedList for manipulation.

Is ArrayList faster than LinkedList?

LinkedList is faster than ArrayList while inserting and deleting elements, but it is slow while fetching each element.

Can sorting be done in LinkedList?

Merge sort is one of the most famous divide-and-conquer sorting algorithms. This algorithm can be used to sort values in any traversable data structure (i.e., a linked list).

Why is LinkedList better than list?

In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.


2 Answers

Up to Java 7, it made no difference because Collections.sort would dump the content of the list into an array.

With Java 8, using an ArrayList should be slightly faster because Collections.sort will call List.sort and ArrayList has a specialised version that sorts the backing array directly, saving a copy.

So bottom line is ArrayList is better as it gives a similar or better performance depending on the version of Java.

like image 170
assylias Avatar answered Sep 19 '22 19:09

assylias


If you're going to be using java.util.Collections.sort(List) then it really doesn't matter.

If the List does not implement RandomAccess, then it will be dumped to a List The list will get dumped into an array for purposes of sorting anyway.

(Thanks for keeping me honest Ralph. Looks like I confused the implementations of sort and shuffle. They're close enough to the same thing right?)

like image 39
corsiKa Avatar answered Sep 21 '22 19:09

corsiKa