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.

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("Enter 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("Array After sorting:");
        for (int i = 0; i < n; i++) {
            System.out.print(" "+a[i]);
        }

    }
}

Output:

Enter size of an array:5
Enter array elements:10 30 20 50 40
Array After sorting: 10 20 30 40 50