java

Java Program to Sort an Array in Ascending and Descending Order

Sometimes we have to sort an array in Java luckily the java.util.Arrays class provides several utility methods to sort java arrays of any type, eg object, int, String, etc. The Arrays class is located in java.util package and exposes all methods related to sorting. you can access the sort() method as Arrays.sort() and just pass your array and it will sort that array.
 

Program to Sort an Array in Ascending Order
import java.util.Arrays; 
  
public class Main 
{ 
    public static void main(String[] args) 
    { 
        int[] arr = {5, 1, 8, 0, 9, 4}; 
  
        Arrays.sort(arr); 
  
        System.out.printf("arr[] : %s", Arrays.toString(arr)); 
    }
}

Output:

arr[] : [0, 1, 4, 5, 8, 9]

 
[st_adsense]  

Program to Sort an Array in Descending Order

In the following example we have Integer[] here instead of int[] because Collections.reverseOrder does not work for primitive types.

import java.util.Arrays; 
import java.util.Collections; 
  
public class Main 
{ 
    public static void main(String[] args) 
    { 
        Integer[] arr = {5, 1, 8, 0, 9, 4}; 
  
        Arrays.sort(arr, Collections.reverseOrder());
  
        System.out.printf("arr[] : %s", Arrays.toString(arr)); 
    }
}

Output:

arr[] : [9, 8, 5, 4, 1, 0]
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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