The following program demonstrates how to perform Sorting an Array in Java.
In order to arrange the elements of the array in ascending order, we compare the consecutive elements of the array. When the first element is greater than the second one, we swap them. This process is repeated for the number of times the element count. So we start a for loop that iterates over each element of the array. The inner for loop checks the two consecutive elements starting from the current element and swaps when the order is violated.
public class Exercise6
{
public static void main(String[] args) {
int[] myarray={3, 5, 1, 12, 9, 24, 6, 8};
System.out.println("Array Elements...");
for(int i=0;i<myarray.length;i++)
{
System.out.println(myarray[i]+"\t");
}
for(int i=0;i<myarray.length-1;i++)
{
for(int j=i+1;j<myarray.length;j++)
{
if(myarray[i]>myarray[j])
{
int temp=myarray[i];
myarray[i]=myarray[j];
myarray[j]=temp;
}
}
}
System.out.println("\nSorted Array Elements...");
for(int i=0;i<myarray.length;i++)
{
System.out.println(myarray[i]+"\t");
}
}
}
Output