Java

Sorting in Ascending Order in Java

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

The output of the Program Demonstrating Sorting in Ascending Order in Java
The output of the Program Demonstrating Sorting in Ascending Order in Java

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

The output of the Program Demonstrating Sorting in Descending Order in Java
The output of the Program Demonstrating Sorting in Descending Order in Java
programmingempire

You may also like...