Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Sorting Arrays

JavaFAQ Home » Java Notes by Fred Swartz Go to all tips in Java Notes by Fred Swartz


Bookmark and Share

Why you shouldn't write your own sort

A favorite computer science topic it sorting, putting a collection of data in some order. Typically this is done for arrays. Many sorts are typically shown, both the O(n2) sorts (eg, selection, insertion, and bubble sorts) and O(n log n) sorts (quick sort, heap sort, etc). These are interesting problems, give students a lot of practice with arrays, bring up important tradeoffs, and are generally quite educational. However, the Java library already has sort methods that are more efficient, more general, and more correct than anything you are likely to write yourself. And they are already written. Professional programmers use one of the java.util.Arrays.sort() methods; they do not write their own, except perhaps in unusual cases.

Other data structures. There are also sort methods in the java.util.Collections class which can be used to sort other kinds of data structures, and there are data structures such as TreeMap that keep elements sorted based on a key.

Sorting Arrays

The java.util.Arrays class contains a number of static methods for sorting arrays, both arrays of primitive types and Object types. The sort method can be applied to entire arrays, or only a particular range.
MethodDescription
Arrays sort methods
Arrays.sort(pa);Sorts the elements of the array of a primitive type into ascending order using their natural ordering.
Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.
Arrays.sort(oa);Sorts the elements of the array of an object type into ascending order, using the order defined by Comparable interface, which defines the compareTo method. Note that many Java classes such as String (but not StringBuffer), Double, BigInteger, etc implement Comparable.
Arrays.sort(oa, from, to); Sorts the elements of the array, in the range from...to of an object type into ascending order.
Arrays.sort(oa, comp);Sorts the elements of the array of an object type into ascending order, using the Comparator comp.
Arrays.sort(oa, from, to, comp); Sorts the elements of the array, in the range from...to of an object type into ascending order using the Comparator comp.

Example - Sorting a full array of Doubles

This example sorts an entire array of objects. Because Double implements the Comparable interface (ie, defines the compare() method), there is no need to define a comparator. This sorts the entire array, but another version sorts in a specified subscript range.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
// arrays/-objectsort/Dblsrt.java
// Fred Swartz 2003-09-15

import java.util.*;

public class Dblsrt {
    public static void main(String[] args) {
        Double[] da = {new Double(3.1), new Double(99), new Double(-66)};
        print(da);         // Print unsorted array.
        Arrays.sort(da);   // Sort array
        print(da);         // Print sorted array.
    }
    
    private static void print(Object[] oa) {
        for (int i=0; i

Comparators

The java.util.Comparator interface can be used to create objects for use in the Arrays.sort methods, among others. A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1

The example below gets the subfiles (children) of a directory, and sorts them alphabetically with the directories first.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
// arrays/-filelist/Filelistsort.java - List contents of directory.
// Takes directory name as command line parameter.
// Fred Swartz - 2003-09-15

import java.util.Arrays;
import java.util.Comparator;
import java.io.*;

public class Filelistsort {
    public static void main(String[] args) {
        File dir = new File(args[0]);
        
        File[] children = dir.listFiles();

        Arrays.sort(children, new Comparator() {
            public int compare(Object a, Object b) {
                File filea = (File)a;
                File fileb = (File)b;
                //--- Sort directories before files, 
                //    otherwise alphabetical ignoring case.
                if (filea.isDirectory() && !fileb.isDirectory()) {
                    return -1;
                } else if (!filea.isDirectory() && fileb.isDirectory()) {
                    return 1;
                } else {
                    return filea.getName().compareToIgnoreCase(fileb.getName());
                }
            }
        });
        
        for (int i=0; i

Sorting ArrayLists

   Collections.sort(alist);
   Collections.sort(alist, comparator);

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy