Pages

Sort an Array Elements in Ascending Order in Java



Sort an Array Elements in Ascending Order in Java

Sort array elements in ascending order in java is very simple and easy just need for loop, if else statements and bubble sort technique. Here i will show you how to write Java program to sort array elements in ascending order

import java.util.Scanner;
public class Sort_Array_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 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("Elements in Ascending Order:");
        for (int i = 0; i < n - 1; i++)
        {
            System.out.print(a[i] + ",");
        }
        System.out.print(a[n - 1]);
    }
}

Output:

Enter no. of elements you want in array: 4
Enter the elements:
20
43
10
67
Elements in Ascending Order:
10
20
43
67


No comments:

Post a Comment

 

Most Reading