Programmingempire
This article demonstrates Sorting in Ascending Order in Java. In fact, array sorting is used in nearly every kind of computer application. It is an important algorithm that we must implement efficiently. Moreover, we can implement sorting in many ways. According, several kinds of sorting algorithms exist. For instance, we have bubble sort, insertion sort, selection sort, heap sort, quick sort, and merge sort. Further, the time complexity of these algorithms is as high as O(n2). Besides, at the lower level, the time complexity of quicksort is O(nlogn).
Program for Sorting in Ascending Order in Java
The following program implements sorting in ascending order.
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
int myarray[]=new int[5];
int i,j,temp;
BufferedReader bfrd=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<myarray.length;i++)
{
System.out.print("Enter element no."+(i+1)+" :- ");
myarray[i]=Integer.parseInt(bfrd.readLine());
}
for(i=0;i<myarray.length;i++)
{
for(j=0;j<myarray.length;j++)
{
if(myarray[i]<myarray[j])
{
temp=myarray[i];
myarray[i]=myarray[j];
myarray[j]=temp;
}
}
}
System.out.println("Elements in ascending order are :- ");
for(i=0;i<myarray.length;i++)
{
System.out.print(myarray[i]+" ");
}
}
}
Output

Program for Sorting in Descending Order in Java
The following program implements sorting in descending order.
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
int myarray[]=new int[5];
int i,j,temp;
BufferedReader bfrd=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<myarray.length;i++)
{
System.out.print("Enter element no."+(i+1)+" :- ");
myarray[i]=Integer.parseInt(bfrd.readLine());
}
for(i=0;i<myarray.length;i++)
{
for(j=0;j<myarray.length;j++)
{
if(myarray[i]>myarray[j])
{
temp=myarray[i];
myarray[i]=myarray[j];
myarray[j]=temp;
}
}
}
System.out.println("Elements in Descending order are :- ");
for(i=0;i<myarray.length;i++)
{
System.out.print(myarray[i]+" ");
}
}
}
Output

- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
