Sorting Arrays in Java

Hello Friends,

I would like to welcome you to my blog.

This is the tutorial for all my java followers. We all must be familiar with arrays and sorting arrays.

Here is a small but very useful tip that every Java programmer should be aware of. Have you ever tried sorting arrays in Java? Well, java.util.Arrays class has built in method to make your job easy. You can use following method to sort any array in Java.

Let us check an example were we will sort an array of String in ascending as well as descending order. Here is a string array we defined in Java.

Output:

In above code we simple define an array of String and printed its value. Now lets sort this array in ascending order using Arrays.sort() method.

Sort in Ascending Order

Output:

Note that we just sorted an array of String in ascending order using sort method. Wasn’t it easy..

Sort in Descending Order

Now lets try to sort the array in reverse order. For this we will use a different signature of sort method.

Following is the code to sort array in reverse order.

Output:

Selective Sorting

Using Arrays.sort() method it is possible to sort an array selectively. i.e. if you want a subpart of array to be sorted, that is possible using following method.

In following code we are sorting the array starting from index 3 till the end.

Output:

Hope this will help you.
Thanks and regards,
Nikhil Naoghare.

4 thoughts on “Sorting Arrays in Java”

  1. found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.