Java Program to Sort the Array in an Ascending and Descending Order

Ascending Order:

package javabasics;

import java.util.Arrays;

public class SortingNumbers {

	public static void main(String[] args) 
	{
		// Initializing unsorted int array
		int Arr[] = {2, 1, 8, 6, 4,25,5,19};

		// let us print all the elements available in list
		for (int number : Arr) {
		System.out.println("Number = " + number);
		}

		// sorting array
		Arrays.sort(Arr);

		// let us print all the elements available in list
		System.out.println("The sorted int array is:");
		for (int number : Arr) {
		System.out.println("Number = " + number);
		}

	}

}
package javabasics;

import java.util.Scanner;

public class AscendingOrder {

	public static void main(String[] args) 
	{
		int num, i, j, temp;
		
		Scanner input = new Scanner(System.in);
	 
	    System.out.println("Enter the number of integers to sort:");
	    
	    num = input.nextInt();
	 
	    int array[] = new int[num];
	 
	    System.out.println("Enter " + num + " integers: ");
	 
	    for (i = 0; i < num; i++) 
	    
	    array[i] = input.nextInt();
	 
	    for (i = 0; i < ( num - 1 ); i++) {
	      for (j = 0; j < num - i - 1; j++) {
	        if (array[j] > array[j+1]) 
	        {
	           temp = array[j];
	           array[j] = array[j+1];
	           array[j+1] = temp;
	        }
	      }
	    }
	 
	    System.out.println("Sorted list of integers:");
	 
	    for (i = 0; i < num; i++) 
	      System.out.println(array[i]);

	}

}

Descending Order:

package javabasics;

import java.util.Scanner;

public class DescendingOrder {

	public static void main(String[] args) {
		int num, i, j, temp;
	    Scanner input = new Scanner(System.in);
	 
	    System.out.println("Enter the number of integers to sort:");
	    num = input.nextInt();
	 
	    int array[] = new int[num];
	 
	    System.out.println("Enter " + num + " integers: ");
	 
	    for (i = 0; i < num; i++) 
	      array[i] = input.nextInt();
	 
	    for (i = 0; i < ( num - 1 ); i++) {
	      for (j = 0; j < num - i - 1; j++) {
	        if (array[j] < array[j+1]) 
	        {
	          temp = array[j];
	          array[j] = array[j+1];
	          array[j+1] = temp;
	        }
	      }
	    }
	 
	    System.out.println("Sorted list of integers:");
	 
	    for (i = 0; i < num; i++) 
	      System.out.println(array[i]);
		

	}

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *