[java] Ascending and Descending Number Order in java

I'm doing an ascending and descending order number in java and here's my code:

System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
int arr[] = new int[num1];

for (int i = 0; i<num1; i++) {
    System.out.print("Enter Value #" + (i + 1) + ":");
    arr[i] =Integer.parseInt(in.readLine());
}

System.out.print("Numbers in Ascending Order:" );

for(int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.print( " " +arr[i]);
}

System.out.println(" ");
System.out.print("Numbers in Descending Order: " );

Currently, the code generates the following:

Enter How Many Inputs: 5
Enter Value #1:3
Enter Value #2:5
Enter Value #3:6
Enter Value #4:11
Enter Value #5:2
Numbers in Ascending Order: 2 3 5 6 11 
Numbers in Descending Order: 

So, the Arrays.sort(arr) call seems to work - but I'm looking for a similarly simple way to provide the descending sort, and can't find it in the documentation. Any ideas?

This question is related to java

The answer is


Arrays.sort(arr, Collections.reverseOrder());
for(int i = 0; i < arr.length; i++){
    System.out.print( " " +arr[i]);
}

And move Arrays.sort() out of that for loop.. You are sorting the same array on each iteration..


Just sort the array in ascending order and print it backwards.

Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
    //print arr[i]
}

public static void main(String[] args) {
          Scanner input =new Scanner(System.in);
          System.out.print("enter how many:");
         int num =input.nextInt();
    int[] arr= new int [num];
    for(int b=0;b<arr.length;b++){
   System.out.print("enter no." + (b+1) +"=");
   arr[b]=input.nextInt();
    }

    for (int i=0; i<arr.length;i++) {
        for (int k=i;k<arr.length;k++) {

        if(arr[i] > arr[k]) {

        int temp=arr[k];
        arr[k]=arr[i];
        arr[i]=temp;
        }
            }

    }
    System.out.println("******************\n output\t accending order");


    for (int i : arr){
        System.out.println(i);
    }
}
}

use reverse for loop to print in descending order,

for (int i = ar.length - 1; i >= 0; i--) {
    Arrays.sort(ar);
    System.out.println(ar[i]);
}

int arr[] = { 12, 13, 54, 16, 25, 8, 78 };

for (int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.println(arr[i]);
}

Three possible solutions come to my mind:

1. Reverse the order:

//convert the arr to list first
Collections.reverse(listWithNumbers);
System.out.print("Numbers in Descending Order: " + listWithNumbers);

2. Iterate backwards and print it:

Arrays.sort(arr);
System.out.print("Numbers in Descending Order: " );
for(int i = arr.length - 1; i >= 0; i--){
  System.out.print( " " +arr[i]);
}

3. Sort it with "oposite" comparator:

Arrays.sort(arr, new Comparator<Integer>(){
   int compare(Integer i1, Integer i2) {
      return i2 - i1;
   }
});
// or Collections.reverseOrder(), could be used instead
System.out.print("Numbers in Descending Order: " );
for(int i = 0; i < arr.length; i++){
  System.out.print( " " +arr[i]);
}

You could take the ascending array and output in reverse order, so replace the second for statement with:

for(int i = arr.length - 1; i >= 0; i--) {
    ...
}

If you have Apache's commons-lang on the classpath, it has a method ArrayUtils.reverse(int[]) that you can use.

By the way, you probably don't want to sort it in every cycle of the for loop.


Sort the array just as before, but print the elements out in reverse order, using a loop that counts down rather than counting up.

Also, move the sort out of the loop - you are currently sorting the array over and over again when you only need to sort it once.

                Arrays.sort(arr);
                for(int i = 0; i < arr.length; i++){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }
                for(int i = arr.length-1; i >= 0; i--){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }

You can sort the array first, and then loop through it twice, once in both directions:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 

Why are you using array and bothering with the first question of number of wanted numbers ?

Prefer an ArrayList associated with a corresponding comparator:

List numbers = new Arraylist();
//add read numbers (int (with autoboxing if jdk>=5) or Integer directly) into it

//Initialize the associated comparator reversing order. (since Integer implements Comparable)
Comparator comparator = Collections.reverseOrder();

//Sort the list
Collections.sort(numbers,comparator);

package pack2;

import java.util.Scanner;

public class group {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner data= new Scanner(System.in);
    int value[]= new int[5];
    int temp=0,i=0,j=0;
    System.out.println("Enter 5 element of array");
    for(i=0;i<5;i++)
    value[i]=data.nextInt();
     for(i=0;i<5;i++)
     {
     for(j=i;j<5;j++)
     {
      if(value[i]>value[j])
      {
       temp=value[i];
       value[i]=value[j];
       value[j]=temp;
      }
     }

     }
      System.out.println("Increasing Order:");
      for(i=0;i<5;i++)
           System.out.println(""+value[i]); 
    }

you can make two function one for Ascending and another for Descending the next two functions work after convert array to List

public List<Integer> sortDescending(List<Integer> arr){
    Comparator<Integer> c = Collections.reverseOrder();
    Collections.sort(arr,c);
    return arr;
  }

next function

public List<Integer> sortAscending(List<Integer> arr){   
    Collections.sort(arr);
    return arr;
  }

I have done it in this manner (I'm new in java(also in programming))

import java.util.Scanner;

public class SortingNumbers {

public static void main(String[] args) {
    Scanner scan1=new Scanner(System.in);
    System.out.print("How many numbers you want to sort: ");
    int a=scan1.nextInt();

    int i,j,k=0; // i and j is used in various loops.
    int num[]=new int[a];
    int great[]= new int[a];    //This array elements will be used to store "the number of being greater."  

    Scanner scan2=new Scanner(System.in);
    System.out.println("Enter the numbers: ");

    for(i=0;i<a;i++)    
        num[i] = scan2.nextInt();

    for (i=0;i<a;i++) {
        for(j=0;j<a;j++) {
            if(num[i]>num[j])   //first time when executes this line, i=0 and j=0 and then i=0;j=1 and so on. each time it finishes second for loop the value of num[i] changes.
                k++;} 
    great[i]=k++;  //At the end of each for loop (second one) k++ contains the total of how many times a number is greater than the others.
    k=0;}  // And then, again k is forced to 0, so that it can collect (the total of how many times a number is greater) for another number.

    System.out.print("Ascending Order: ");
    for(i=0;i<a;i++)
        for(j=0;j<a;j++)
            if(great[j]==i) System.out.print(num[j]+","); //there is a fixed value for each great[j] that is, from 0 upto number of elements(input numbers).
    System.out.print("Discending Order: ");
    for(i=0;i<=a;i++)
        for(j=0;j<a;j++)
            if(great[j]==a-i) System.out.print(+num[j]+",");
}

}