Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

[an error occurred while processing this directive]

Java Notes

Sorting Arrays

[an error occurred while processing this directive]

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. Textbooks cover both the slow, O(n2), sorts (eg, selection, insertion, and bubble sorts) and fast, 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 sort methods in the java.util.Collections class which can be used to sort other kinds of data structures (eg, ArrayList), and there are data structures such as TreeMap that keep elements sorted based on a key.

Sorting Arrays with Arrays.sort(...)

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 arrays using Arrays.sort()

This example sorts an array of Strings and an array of doubles. All object types that implement Comparable (ie, defines compareTo() method), can be sorted with using a comparator. The Arrays.sort() method is also defined for primitive arrays.

  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 
// File   : arrays/-objectsort/Dblsrt.java
// Purpose: To show how Arrays.sort() works with objects
//          that implement Comparable (ie, define compareTo().
//          It will also sort primitive types.
// Author : Fred Swartz 2006-03-10.  Public domain.

import java.util.Arrays;

public class Dblsrt {
    //========================================================= main
    public static void main(String[] args) {
        //... Sort strings - or any other Comparable objects.
        String[] names = {"Zoe", "Alison", "David"};
        print(names);       // Print unsorted array.
        Arrays.sort(names); // Sort array
        print(names);       // Print sorted array

        //... Sort doubles or other primitives.
        double[] lengths = {120.0, 0.5, 0.0, 999.0, 77.3};
        Arrays.sort(lengths);
        for (double d : lengths) {
            System.out.print(d + " ");
        }
        System.out.println();
    }

    //======================================================== print
    // Print array of any objects using their toString() method.
    private static void print(Object[] oa) {
        for (Object obj : oa) {
            System.out.print(obj + " ");
        }
        System.out.println();
    }
}

Comparators

All sorts that Java uses are comparison sorts, which means that they make all ordering decisions by comparing two values. If there is no natural ordering, or you don't want to use it, you can specify a Comparator to use in comparing two values. See Comparators.

Sorting ArrayLists

In a similar way, you can use the methods below to sort ArrayLists.

   Collections.sort(alist);
   Collections.sort(alist, comparator);
Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (post your own) View All Comments Latest 10 Comments:

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.