Home » Java programs » Java array programs

Java program to sort a one dimensional array in ascending order



Here, we are implementing a java program to sort an array (one-dimensional array) in ascending order? We are reading array elements, arranging them in ascending order and printing the sorted array.
Submitted by IncludeHelp, on December 07, 2017

Given an array and we have to sort its elements in ascending order and print the sorted array using java program.

Example:

    Input:
    Array (elements will be read in program): 25 54 36 12 48 88 78 95 54 55
    Output:
    Sorted List in Ascending Order : 
    12  25  36  48  54  54  55  78  88  95  

Program to sort an array in ascending order in java

import java.util.Scanner;

public class ExArraySort
{
   public static void main(String args[])
   {
	   // initialize the objects.
       int n, i, j, temp;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       // enter number of elements to enter.
       System.out.print("Enter number for the array elements : ");
       n = scan.nextInt();
	   
       // enter elements.
       System.out.println("Enter " +n+ " Numbers : ");
       for(i=0; i<n; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       // sorting array elements.
       System.out.print("Sorting array : \n");
       for(i=0; i<(n-1); i++)
       {
           for(j=0; j<(n-i-1); j++)
           {
               if(arr[j] > arr[j+1])
               {
                   temp = arr[j];
                   arr[j] = arr[j+1];
                   arr[j+1] = temp;
               }
           }
       }
	   
       System.out.print("Array Sorted Successfully..!!\n");
	   
       // array in ascending order.
       System.out.print("Sorted List in Ascending Order : \n");
       for(i=0; i<n; i++)
       {
           System.out.print(arr[i]+ "  ");
       }
   }
}

Output

Enter number for the array elements : 10
Enter 10 Numbers : 
25
54
36
12
48
88
78
95
54
55
Sorting array : 
Array Sorted Successfully..!!
Sorted List in Ascending Order : 
12  25  36  48  54  54  55  78  88  95  





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.