File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Sorting in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting in Java" Watch "Sorting in Java" New topic

Sorting in Java

Vivek Jain
Ranch Hand

Joined: Oct 17, 2007
Posts: 34
2 Questions:
1. If I want to sort objects not more than 50, how do I do it, i mean collections.sort or something else???

2. If I want to sort more than 1000 objects, how do i do it???

Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33107

Collections.sort() will work with any size collection.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Vivek Jain
Ranch Hand

Joined: Oct 17, 2007
Posts: 34
I know it'll work but which is the best efficient method???
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Collections.sort() is just one method. It's the best choice in general for the vast majority of situations you might find yourself in.

If you really need to optimize beyond that, you will need to be much more speicfic about the specific situation you're dealing with. There is no single method that is always the best - it depends on the situation. There are many different sorting algorithms which are possible, and many of them are optimized for particular situations. The modified heapsort used by Collections.sort() is a good all-around algorithm, but it's not always the best. Feel free to implement an alternate algorithm if it's better for your particular dataset.

"I'm not back." - Bill Harding, Twister
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

the answer to almost every software question of the nature "What is the best way to do XYX" is usually "It depends".

You can take a semester long college class on algorithms (I did). You learn how to analyze your data and which algorithm is the best for that situation.

This is not true just for sorting, although sorting and searching are a BIG chunk of it.

So, without knowing anything about your data, there is no 'best' answer. A bubble sort might be the best, or a quick sort.

Heck, even for several thousand objects, it may not make much difference. But it might.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Sorting in Java
It's not a secret anymore!