Java Programming | Sorting the Elements in Array

Introduction.

This is a tutorial for creating a java program to sort the elements in array in ascending or descending order. The program is given below that takes the array from user and sorts and prints the sorted array. Go enjoy the program. Lets begin…

Program for sorting elements in ascending order of array in java.

//import Scanner as we require it.
import java.util.Scanner;
 
// the name of our class its public
public class SortArray {
    //void main
        public static void main (String[] args)
        {
            //declare int
            int a[] = new int[10],i,j,temp,n=10;
            //declare scanner object.
            Scanner input = new Scanner(System.in);
            //a loop to enter elements of array.
            for(i=0;i<n;i++)
            {
            System.out.println("Enter number:");
            a[i] = input.nextInt();
            }
            //Print the Sorted array
            System.out.println("Sorted Array:-");
            //sort the array.
            for(i=0;i<n-1;i++)
            {
              for(j=0;j<n-i-1;j++)
              {
                if(a[i]<a[j])
                {
                 temp = a[i];
                 a[i] = a[j];
                 a[j] = temp;
                }
              }
            }
            //print the sorted array
            for(i=0;i<n;i++)
            {
                System.out.println(a[i]);
            }
 
        }
}

Output

Enter number: 10
Enter number: 9
Enter number: 3
Enter number: 63
Enter number: 12
Enter number: 72
Enter number: 654
Enter number: 1
Enter number: 2
Enter number: 6
Sorted Array:-
1
2
3
6
9
10
12
63
72
654

How does it work

  1. You enter the array.
  2. The array is sorted.
  3. The array is printed.

Extending it

The program cannot be extended.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter number.
  5. Declare input as Scanner.
  6. Take the array and save it in variables.
  7. Add two loop and sort the array.
  8. Print the sorted array.

At the end.

You learnt creating the Java program for Sorting the Element in Array. So now enjoy the program.

Please comment on the post and share it.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: