Search This Blog

Wednesday, 9 April 2014

java program to sort an array

java program to sort an array


import java.util.Arrays;

public class SortingArrays {
       public static void main(String[] args) {
              String[] unsortStrArr = { "one""two""three""four""five""six"};
              int[] unsortIntArr = new int[] { 9, 6, 4, 1, 4, 98 };
              System.out.println("String Array Elements Before sorting");
              displayStringArrayElements(unsortStrArr);

              System.out.println("int array elements Before sorting");
              displayIntArrayElements(unsortIntArr);

              // public static void sort(Object[] a)
              // Sorts the specified array of objects into ascending order, according
              // to the natural ordering of its elements.
              Arrays.sort(unsortStrArr);
              System.out.println("String array elements after sorting");
              displayStringArrayElements(unsortStrArr);

              Arrays.sort(unsortIntArr);
              System.out.println("int array elements after sorting");
              displayIntArrayElements(unsortIntArr);
       }

       public static void displayIntArrayElements(int[] intArr) {
              for (int temp : intArr) {
                     System.out.println(temp);
              }
              System.out.println(".............................");

       }

       public static void displayStringArrayElements(String[] strArr) {
              for (String temp : strArr) {
                     System.out.println(temp);
              }
              System.out.println("..........................");
       }
}
OUTPUT 
String Array Elements Before sorting
one
two
three
four
five
six
..........................
int array elements Before sorting
9
6
4
1
4
98
.............................
String array elements after sorting
five
four
one
six
three
two
..........................
int array elements after sorting
1
4
4
6
9
98
.............................

No comments:

Post a Comment