Sorting an Array (standard)

Its been a while since we talk about arrays in Java, and yet we haven’t talk about how to sort an Array itself. Well today I’m gonna redeem that, today we’ll talk about how to sort an Array (In Java *of course).

Syntax
Look at this syntax for Sorting an Array :
public static void sort(int[] a) //the a– parameter is the array that is to be sorted.

 Exmpl :

//1st we import
import java.util.Arrays;
public class ArrayDemo {

//2nd we create the main method
   public static void main(String[] args) { 
   int sortArr[] = {9, 1, 2, 6, 4}; //here we initialize as a normal array
 

   for (int number : sortArr) {
   System.out.println(“Number : ” + number); //here we print out as its normal
   }

   // sorting array

   Arrays.sort(sortArr);  //here we sort the array

   // let us print all the elements available in list
   System.out.println(“Now its sorted, output of int array is:”);
   for (int number : sortArr) {
   System.out.println(“Number : ” + number); //here we print the already sorted array
   }
   }

And when we run this code, the magic happens 😀 :

Number : 9
Number : 1
Number : 2
Number : 6
Number : 4

Now its sorted, output of int array is:
Number : 1
Number : 2
Number : 4
Number : 6

Number : 9 

One thought on “Sorting an Array (standard)”

Leave a Reply

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