Win a copy of Grokking Bitcoin this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

Maintain sorted order or Insertion Sort  RSS feed

 
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!
 
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.
 
Marshal
Posts: 64115
215
  • 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.
 
author & internet detective
Posts: 39235
727
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.
 
You'll never get away with this you overconfident blob! The most you will ever get is this tiny ad:
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!