Write a Java Program to Sort the Array in an Ascending Order.
Enter the size of the array, and then enter all the elements of that array. Then, the program uses a for loop to sort the array in ascending order by comparing each element of the array with all the other elements in the array. If an element is smaller than the other elements, it is swapped with the larger element. This process is repeated until the entire array is sorted in ascending order.
Example:
Original Array:
4 | 3 | 2 | 6 | 1 |
Sorted Array:
1 | 2 | 3 | 4 | 6 |
Here is the source code of the Java Program to Sort the Array in an Ascending Order. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/*
* Java Program to Sort an Array in Ascending Order
*/
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
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;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
1. The program begins by importing the Scanner class to take input from the user.
2. A class called Ascending_Order is defined.
3. The main method is created with a Scanner object and two integer variables: n and temp.
4. It prompts the user to enter the size of the array and each element of the array.
5. The first for loop is used to traverse the array.
6. The nested for loop is used to compare each element of the array with all the other elements in the array.
7. If the first element is greater than the second element, the two elements are swapped using a temporary variable.
8. The sorted array is printed in ascending order using a for loop.
$ javac Ascending _Order.java $ java Ascending _Order Enter no. of elements you want in array:5 Enter all the elements: 4 3 2 6 1 Ascending Order:1,2,3,4,6
To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.
- Apply for Computer Science Internship
- Check Java Books
- Practice BCA MCQs
- Check Programming Books
- Practice Information Technology MCQs