How to organize random integer values in descending order in a Java array?

Asked

Viewed 14,856 times

2

I need to organize the values that the array receives randomly and leave them in descending order, but honestly I don’t know how to do it, there’s my code, I couldn’t 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
  • You need to implement the sorting algorithm yourself, or you can use a ready-made sorting method available in the JDK?

1 answer

4


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

Crescent 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

Substitute

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

for

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 extend object class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.