ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Program: How to Sort Numbers in an Array in a Descending Order

Updated on June 19, 2013

Java Program: Sort Numbers in Descending Order with a Sample Java Source Code

The Java source code of sorting number in descending order is just slightly different with the java source code of sorting number in ascending order. The algorithm for sorting in descending order is this: If the entered number is greater than the next, the program should do nothing, as we want the greater number to come first. Otherwise, if the number is smaller than the next entered number, the program should swap the 2 numbers in order to meet the goal of sorting in descending order. Then the program will continue to behave like this till all numbers in the array are checked.

Java Source Code for Descending Order

package sort_numbers_in_descending_order;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
       Scanner input = new Scanner(System.in);

       System.out.print("How Many Numbers You Want to Sort? ");
       int size  = input.nextInt();

       int[] newArr = new int [size];

       System.out.print("Enter " + size + " Numbers to Sort: ");

       for(int input_array = 0; input_array<size; input_array++)
       {
           newArr[input_array] = input.nextInt();
       }
       
       for(int enter_number = 0; enter_number < size; enter_number++)
       {
            for(int sort_num = 1; sort_num < size; sort_num++)
            {

                if(newArr[sort_num] > newArr[sort_num-1])
                {
                    int swapNum = newArr[sort_num];
                    newArr[sort_num] = newArr[sort_num-1];
                    newArr[sort_num-1] = swapNum;
                }

            }
         
       }
       

       System.out.println("Here are the Sorted Numbers: ");
       
       for(int printNum=0; printNum<size; printNum++)
       {
           System.out.print(newArr[printNum] + " ");
           
       }
       System.out.println();
    }

}

Sample Output:

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article