Java Program to sort the elements of an array in ascending order

In this tutorial you will learn about the Java Program to sort the elements of an array in ascending order and its application with practical example.

In this tutorial, we will learn to create a Java Program to sort the elements of an array in ascending order using java programming.

Prerequisites

Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:

  • Java Operators.
  • Basic Input and Output function in Java.
  • Class and Object in Java.
  • Basic Java programming.
  • If-else statements in Java.
  • For loop in Java.

Algorithm

  • STEP 1: START
  • 2: Ask user to enter size of an array.
  • 3:Then take elements of an  array
  • 4: iterate each value through loop.
  • 5 for (int i = 0; i < number; i++)
  •             {
  •            for (int j = i + 1; j < number; j++)
  •            {
  •            if(arr[i]>arr[j]) then
    temp = arr[i]
    arr[i]=arr[j]
    arr[j]=temp
  •            }
  •           }
  • STEP 6:  PRINT “Elements of array sorted in ascending order”
  • STEP 7: for (int i = 0; i < number – 1; i++)
  •              {
  •             System.out.print(arr[i] + “,”);
  •               }
  •              System.out.print(arr[number – 1]);
  • STEP 8: END

Java Program to sort the elements of an array in ascending order

In this program we will take size of an array  and sort the elements of an array using nested for loop. We would first declared and initialized the required variables. Next, we will sort the elements in an array. Lets have a look at the code.

Output

Sorted elements in an array.

In the above program, we have first declared and initialized a set variables required in the program.

  • arr[]= it will hold array values
  • l=  it will hold length of an array.
  • i and j for iteration
  • temp = it will hold temporary value of an array.

After declaring variables we initiate values in  an array[]

Elements will be sorted in a way that the smallest element will show on extreme left which in this case is 1. The largest element will show at extreme right which in this case is 63.As shown in the image below.

Steps to change elements.

  1. Compare elements with each other.
  2. Use nested for loop to keep track.
  3. Swap the elements if the first element is greater than the second element.
  4. this process followed till all the elements in array are sorted.

and finally we will print the sorted elements.

In this tutorial we have learn about the Java Program to sort the elements of an array in ascending order and its application with practical example. I hope you will like this tutorial.