Sunday, February 8, 2015

Sort an array using java Arrays class

There are lot of sorting algorithms to use. but if we are in a hurry or we just want to sort a small set of data using sort() method of java Arrays class is the best thing you can do.
So lets see how to sort an array using java Arrays class.
here is the coding example.

import java.util.Arrays;

public class ArraySort {
public static void main (String[] args){  

  String[] names = { "Nimal", "Sunil", "Tharaka", "Isuru","Anuradha"};
  int[] intNumbers = { 3, 5, 12, 7, 1, 9};
  double[] doubleNumbers = { 2.34, 45.213, 4.76, 4.23, 8.32};  

  //sorting String array 'names'
  Arrays.sort(names);  

  int i=1;
  System.out.println("After sorting String array");
  for(String name:names)
   System.out.println("item"+i+++" - "+name);  

  //sorting int array 'intNumbers'
  Arrays.sort(intNumbers);    

  i=1;
  System.out.println("After sorting int array");
  for(int num:intNumbers)
   System.out.println("item"+i+++" - "+num);   

  //sorting double array 'doubleNumbers'
  Arrays.sort(doubleNumbers);    

  i=1;
  System.out.println("After sorting double array");
  for(double num:doubleNumbers)
   System.out.println("item"+i+++" - "+num);  

 }
}

Output for this code will be like this.

After sorting String array
item1 - Anuradha
item2 - Isuru
item3 - Nimal
item4 - Sunil
item5 - Tharaka
After sorting int array
item1 - 1
item2 - 3
item3 - 5
item4 - 7
item5 - 9
item6 - 12
After sorting double array
item1 - 2.34
item2 - 4.23
item3 - 4.76
item4 - 8.32
item5 - 45.213

This Arrays.sort() method support not only for String, int and double arrays but also for byte, char, long, float and object arrays

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...