Home » Java programs » Java Array programs

Java program to sort an array in ascending order

In this java program, we are going to learn how to read an integer array and sort array in ascending order?
Submitted by IncludeHelp, on November 01, 2017

Given an array of integers and print array in ascending order using java program.

Example:

Input:  12, 25, 99, 66, 33, 8, 9, 54, 47, 36
Output: 8, 9, 12, 25, 33, 36, 47, 54, 66, 99

In this java program, we are reading total number of elements (N) first, and then according the user input (value of N)/total number of elements, we are reading the elements. Then sorting elements of array in ascending order and then printing the elements which are sorted in ascending order.

Program

import java.util.Scanner;

public class ExArraySortElement 
{
	public static void main(String[] args) 
	{
		int n, temp;
		//scanner class object creation
		Scanner s = new Scanner(System.in);

		//input total number of elements to be read
		System.out.print("Enter the elements you want : ");
		n = s.nextInt();

		//integer array object
		int a[] = new int[n];

		//read elements 
		System.out.println("Enter all the elements:");
		for (int i = 0; i < n; i++) 
		{
			a[i] = s.nextInt();
		}

		//sorting elements
		for (int i = 0; i < n; i++) 
		{
			for (int j = i + 1; j < n; j++) 
			{
				if (a[i] > a[j]) 
				{
					temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}

		//print sorted elements 		
		System.out.println("Ascending Order:");
		for (int i = 0; i < n ; i++) 
		{
			System.out.println(a[i]);
		}
	}   
}

Output

Enter the elements you want : 10
Enter all the elements:
12
25
99
66
33
8
9
54
47
36
Ascending Order:
8
9
12
25
33
36
47
54
66
99





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.