How to Sort an array in Ascending Order in Java
In this program, we will learn how to sort array elements in ascending order in Java. The user will give the inputs. on the basis of input, we have to sort the array in ascending order. But before starting the code we should learn something.
- What is scanner class
- How to declare an array in java
Scanner class is available in the util package so we have imported the util package first. If we want to use a scanner class we will have to create a scanner class object.
Syntax of declaring an array in java
int num[] = new int[count];//count is variable which shows the size of an array and int indicates the type of integer.
Sort array elements in Ascending Order in Java
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { int count, temp; //User inputs the array size Scanner scan = new Scanner(System.in); System.out.print("Enter number of elements you want in the array: "); count = scan.nextInt(); int num[] = new int[count]; System.out.println("Enter array elements:"); for (int i = 0; i < count; i++) { num[i] = scan.nextInt(); } scan.close(); for (int i = 0; i < count; i++) { for (int j = i + 1; j < count; j++) { if (num[i] > num[j]) { temp = num[i]; num[i] = num[j]; num[j] = temp; } } } System.out.print("Array Elements in Ascending Order: "); for (int i = 0; i < count - 1; i++) { System.out.print(num[i] + ", "); } System.out.print(num[count - 1]); } }
In the program first, we import the util package after that we create a class and declare the variables. After that, we use a scanner class for the inputs and declare an array of size ‘count’. The count is variable which the size of the array and value of count is decided by the user. After that, we use for each loop for the inputs. After that, we use the second for each loop which is used for comparing the elements & the third loop is used for the printing sorted elements.
The output of the program
Enter the elements you want in an array: 5 Enter Array Elements: 5 6 3 2 Sorted elements: 2,3,5,6
Learn more,
Leave a Reply