Java Program to Sort a List of Numbers in Ascending and Descending order

Sort a List of Numbers in Ascending and Descending order. Ascending order means arrange smallest number to greatest number and Descending order means greatest number to smallest number.
import java.util.*;
class nosort
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  int i,j,temp;
  System.out.print("Enter a length of number=");
  int l=sc.nextInt();
  int n[]=new int[l];
  System.out.print("Enter list of number:\n");
  for(i=0;i<l;i++)
  {	
   n[i]=sc.nextInt();
  }
  System.out.println("The unsorted list is as follows:\n");
  for(i=0;i<l;i++)
  {
   System.out.print(n[i]+"\t");
  }
  for(i=0;i<l;i++)
  {
   for(j=i+1;j<l;j++)
   {
    if(n[i]>n[j])
    {
     temp=n[i];
     n[i]=n[j];
     n[j]=temp;
    }
   }
  }
  System.out.println("\n\nThe list of number are sorted by Ascending order\n");
  for(i=0;i<l;i++){
  System.out.print(n[i]+"\t");}
  System.out.println("\n\nThe list of number are sorted by Descending order\n");
  for(i=l-1;i>=0;i--){
  System.out.print(n[i]+"\t");}
 }
}

Output:

Enter a length of number=5
Enter list of number:
12
90
33
88
44
The unsorted list is as follows:

12      90      33      88      44

The list of number are sorted by Ascending order

12      33      44      88      90

The list of number are sorted by Descending order

90      88      44      33      12

Java Program to Sort a List of Numbers Using Array

Java program to display a list and sorted list.

import java.util.*;
class List
{
public static void main(String args[])
{
int num[] = {79,82,63,51,40,78,91,66,98,65};
int l=num.length;
int i,temp,j;
System.out.println("The unsorted list is as follows:\n");
for(i=0;i<l;i++)
System.out.print(num[i]+"\t");
for(i=0;i<l;i++)
{
for(j=i+1;j<l;j++)
{
if(num[i]<num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}}
}
System.out.println("\n\nThe sorted list is as follows:\n");
for(i=0;i<l;i++)
System.out.print(num[i]+"\t");
}
}

Output:

The unsorted list is as follows:

79  82  63  51  40  78  91  66  98  65

The sorted list is as follows:

98  91  82  79  78  66  65  63  51  40

Post a Comment

0 Comments