Monday, January 25, 2016

Java array sort in ascending and descending order

In this tutorial, we will study the methods of sorting a table in the ascending and descending order in Java. We'll show you how to use the sort () method to perform the sorting task.

Several methods in Java allow you to sort your tables and use these methods of sorting tables, you will primarily import a library named Arrays. You do it with the keyword import:

import java.util.Arrays;
Here is an example:

import java.util.Arrays;

public class ArraysTest {

   public static void main(String[] args) {

   // array init
   int array[] = {11,87,14,5,63,24};

   // display all the elements before sorting
   for (int value : array) {
      System.out.println("number: " + value);
   }

   // Call Arrays.sort() method
   Arrays.sort(array);

   // display all the elements after sorting
   System.out.println("Sorted array\n");
   for (int value : array) {
      System.out.println("number: " + value);
   }
   }
}
After complilation and execution, we should get that result:

number: 11
number: 87
number: 14
number: 5
number: 63
number: 24
Sorted array

number: 5
number: 11
number: 14
number: 24
number: 63
number: 87

Sort array in descending order

Sorting in descending order is only possible if you write your own code or convert the array into an array of objects, then import collections librairy and call Collections.sort() method. This method sort the array in the ascendeng order, to sort it in the descending order, we call reverse() method that should reverse the result array.

import java.util.Arrays;
import java.util.Collections;

public class ArraysTest {

   public static void main(String[] args) {

   // array init
   int array[] = {11,87,14,5,63,24};

   // display all the elements before sorting
   for (int value : array) {
      System.out.println("number: " + value);
   }

   //create array of integer to store integer objects
   Integer[] integerArray = new Integer[array.length];
   for (int i=0; i < array.length; i++) {
    //create an new integer object and store it
    integerArray[i] = new Integer(array[i]);
   }
  
   // sort the array then inverse it using reverseOrder() method
   Arrays.sort(integerArray, Collections.reverseOrder());

   // display all the elements after sorting
   System.out.println("Sorted array\n");
   for (int value : integerArray) {
      System.out.println("number: " + value);
   }
   }
}
Let us compile and run this program:

number: 11
number: 87
number: 14
number: 5
number: 63
number: 24
Sorted array

number: 87
number: 63
number: 24
number: 14
number: 11
number: 5
References:
Java.util.Arrays.sort(int[]) Method

No comments:

Post a Comment