Sort a Java array in ascending and descending order
An array is a container containing many data of the same type within a single variable in a contiguous manner. It means all data can be of numbers type, string type, etc. In this tutorial, we are going to focus on arrays containing numbers. The same concept is followed for the rest of the other types of arrays. If the array contains all integer types of data, it is called an integer array. If the array contains a string type of data, it is called a string array.
Sorting means arranging in ascending or decreasing order.
Ascending order means arranging the numbers in increasing order.
Descending order means arranging the numbers in decreasing order.
How to declare and initialize an array of strings using the String class:
int a[]={3,4,2,5,1};
Ascending order of above array :
int a[]={1,2,3,4,5};
Descending order of above array :
int a[]={5,4,3,2,1};
Steps to follow: Sorting Java Array
- Create and initialize the array.
- Use
Arrays.sort(<array-name>)
to sort the array in ascending order where Arrays class is present injava.util
package andsort()
is the pre-defined static method which is directly called by class name. - We can arrange in descending order by running the loop in reverse order after sorting in ascending order by using
Arrays.sort(<array-name>)
.
Note: This is not the only method for sorting.
import java.util.*; //it contains the Arrays class and sort() in it public class Main { public static void main(String[] args) { int a[]={3,6,2,7,1,9,8,0}; //declare and initialize the array Arrays.sort(a); //used to sort the array in ascending/increasing order for(int i=0;i<a.length;i++) //it will print the array after arranging in ascending/increasing array { System.out.print(a[i]+" "); } System.out.println(); //it will give a line break in output for(int i=a.length-1;i>=0;i--) //it will print in decreasing/descending order { System.out.print(a[i]+" "); } //we can store it in another array or in same array in reverse order and then print it } }
Output:
0 1 2 3 6 7 8 9 9 8 7 6 3 2 1 0
Leave a Reply