Put vectors in order. JAVA

2

I need to put 5 pesos in order from the smallest to the largest. Defining numbers first, for example: int vet [] = {3,4,2,8,7,1}; it runs right, but I need to do it this way: int vet [] = new int [5]; this way he is only taking 3 numbers as shown in the image. follow the code:

intvet[]=newint[5];intaux;booleancontrole;for(inti=0;i<vet.length;i++){vet[i]=Integer.parseInt(JOptionPane.showInputDialog("Digite o peso: "));

    controle = true;

    for(int j = 0; j < (vet.length -1); j++) {

        if(vet[j] > vet[j+1]) {

            aux = vet[j];
            vet[j] = vet[j + 1];
            vet[j + 1] = aux;
            controle = false;
        }

    }

    if(controle) {

        break;

    }

}
for(int i = 0; i < vet.length; i++) {
System.out.println(vet[i] + "");

}
    
asked by anonymous 13.08.2017 / 06:43

2 answers

1

Well, I've separated your For that completes the% of the For that organizes since you need to have a value to change when it does this reading vet[j] > vet[j+1]) you have a value in j but j + 1 , you have zero start

  public static void main(String args[]) {

        int vet[] = new int [5];

        int aux;

        for(int i = 0; i < vet.length; i++ )
            vet[i] = Integer.parseInt(JOptionPane.showInputDialog("Digite o peso: ",null)); 


    for (int i = 0; i < vet.length; i++)
        {
         for(int j = 0; j < (vet.length); j++) {
         if(vet[i] < vet[j]) {

             aux = vet[i];
             vet[i] = vet[j];
             vet[j] = aux;
         }

      }  
   }
    for(int i = 0; i < vet.length; i++) 
        System.out.println(vet[i] + "");


    }
    
13.08.2017 / 07:07
1

I'm responding as an alternative to Bruno's solution, using Java 8 and Streams. And while it may not be as educational as it is certainly interesting.

The reading part would be equal and separate from the order:

int vet[] = new int [5];

for(int i = 0; i < vet.length; i++ ) {
    vet[i] = Integer.parseInt(JOptionPane.showInputDialog("Digite o peso: "));
}

Now to sort and display would do so:

Arrays.stream(vet).sorted().forEach(x -> System.out.println(x));

The .stream(vet) creates the Stream of integers that will be IntStream . Then .sorted() sorts Stream and finally forEach corresponds to the cycle that was done at the end to show each element.

    
13.08.2017 / 16:23