you’re reading...

Featured

How to sort an array

We normally like to write complex algorithm to sort an array in Java where many of us overlooked the Arrays class in Java which can be very handy in sorting an array.
The Arrays class has a static method called sort which exists in many overloaded versions so you can pass in an array of any primitive type, or pass in an array of Strings or other Objects.
Since it is the reference of the array that is passed to the sort method nothing needs to be returned from it, the array is altered through the reference.
Here’s an example in how the sort static method in Arrays class used to sort array of int and array of Strings


import java.util.Arrays;

public class SortArray
{
public static void main(String args[])
{
/*Initialize and sort int array*/
int arrVal[] = {9,8,6,4,7,5,2,3,1};

Arrays.sort(arrVal);

for(int val : arrVal)
System.out.print(val+" ");

/*Initialize and sort Stirng array*/
String arrStr[] = {"Guan", "Chang", "Gee" };

Arrays.sort(arrStr);

System.out.println("\n");
for(String strval : arrStr)
System.out.print(strval+" ");
}
}

And here’s the output of execution of above code:

1 2 3 4 5 6 7 8 9
Chang Gee Guan