In this tutorial, we will write a program to sort elements of an array in ascending order in java. The number of elements and elements themselves are taken as input from the user.
The program compares the elements and the swap technique is used to arrange the elements in increasing order.
Before that you need to have an idea of the following:
Java Program to Sort Elements in Ascending Order of an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | // sort elements of an array in java. import java.util.Scanner; public class AscendingOrderArray { public static void main(String[] args) { int n, temp; //User inputs Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements for an array: "); n = sc.nextInt(); int ar[] = new int[n]; System.out.println("Enter elements of an array:"); for (int i = 0; i < n; i++) { ar[i] = sc.nextInt(); } sc.close(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (ar[i] > ar[j]) { temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } } } System.out.print("Ascending Order of array elements: "); for (int i = 0; i < n - 1; i++) { System.out.print(ar[i] + ", "); } System.out.print(ar[n - 1]); } } |
Output:
Enter the number of elements for an array:
5
Enter elements of an array:
23
5
76
11
89
Ascending Order of array elements: 5, 11, 23, 76, 89