How to arrange random integer value in descending order in an array in Java?

2

I need to organize the values that the array randomly receives and leaves them in descending order, but I honestly do not know how to do that, here is my code, I could not organize.

package gerarOrganizar;
import java.util.Random;
public class GerarOrganizar {

    public static void main(String[] args) {
        int i=0;
        int[] array = new int[10];
        Random gerador=new Random();
        int[] arrayF= new int[10];
        int j = 0;


        for(i=0;i<10;i++){
            array[i]=gerador.nextInt(25);
            if(array[i]==0)
                i--;
        }//for

        while(j<10){//meu problema começa daqui em diante
            for(j=0;j<10;j++){
                for(i=0;i<10;i++){
                    if(comp<array[i]){
                        comp=array[i];
                        arrayF[j]=array[i];
                    }//if

                }//segundo for
            }//primeiro for
        System.out.println(arrayF[j]);
        }//while    
    }//main
}//class
    
asked by anonymous 08.10.2014 / 21:46

1 answer

4

In java this is much simpler than what you are trying, there is the sort method of static class Arrays made for this. See the full example below:

Ascending Order

package meupacote;
import java.util.Arrays;
import java.util.Random;
public class GerarOrganizar {

    public static void main(String[] args) {
        int[] array = new int[10];
        Random gerador=new Random();
        for(int i=0;i<10;i++){
             array[i]=gerador.nextInt(25);
        }
        //Imprime o Array original
        System.out.println("Antes");
        for(int i: array){
            System.out.println(i);
        }
        // Faz todo o trabalho para você 
        // e de forma mais eficiente do que a que estava tentando
        Arrays.sort(array);
        //Imprime o Array
        System.out.println("Depois");
        for(int i: array)
            System.out.println(i);
        }
    }

See the example running on IDEONE .

Descending order

Replace

int[] array = new int[10]; and Arrays.sort(array);

by

Integer[] array = new Integer[10]; and Arrays.sort(array, Collections.reverseOrder()); respectively.

The reason for such a replacement is that the Arrays.sort (T [] , Comparator) will only work if argument extends the object class.

    
08.10.2014 / 22:00