• Post Reply Bookmark Topic Watch Topic
  • New Topic

Maintain sorted order or Insertion Sort  RSS feed

 
Nick Mario
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone!

I have a list of items in an ArrayList. The list is being added to one at a time and I want to maintain a sorted list. So my question is this: is it more efficient to insert the item in the correct position or to insert the item at the end and then use insertion sort which is extremely fast for very slightly unsorted arrays. I'd really appreciate any help!
 
Nguyen Tuyen
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that you want to sort your ArrayList, if so you don't have to worry about Insertion sort or the way you have import items to your array list, there is a sort function in Collections class for help. Please refer to this link to see the use in detail.
 
Campbell Ritchie
Marshal
Posts: 56218
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is nothing to stop you implementing your own insertion sort algorithm, but it is usually better to use ready‑made methods if possible. Remember the sort() method has been tested by used millions of times.
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37395
531
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have duplicates in your list? If not, you can use a TreeSet which will take care of sorting for you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!