Home >>Java Programs >Java Program to sort the elements of an array in ascending order
In this example, we will create a java program to sort the given array in ascending order such that elements of the array will be arranged from smallest to largest. This can be done through two loops, where the outer loop will select an element and the inner loop will allow us to compare the selected element with the rest of the elements.
public class Main
{
public static void main(String[] args)
{
int [] arr = new int [] {5, 6, 8, 3, 1, 9, 7};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}