Java Program to sort an array in ascending order


In this program, You will learn how to sort an array in ascending order in Java.


Array list in ascending order: 10 20 30 40 50 60


Example: How to sort an array in ascending order in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        int a[] = new int[10];
        int n;

        System.out.print("Enter Size of an Array :");
        n = s.nextInt();
        System.out.print("\nEnter  Array  Elements :");

        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
        }

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

        System.out.print("\nArray After Sorting :");
        for (int i = 0; i < n; i++) {
            System.out.print(" "+a[i]);
        }

    }
}

Output:

Enter Size of an Array :5
Enter  Array  Elements :2 33 44 5 44
Array After Sorting : 2 5 33 44 44