Move the highest value of an Array to the end of it.

Asked

Viewed 127 times

-1

I need to create a method that takes the highest value of an Array and passes it to the end of that Array, so that the array is ordered, without losing any value. I tried several ways and I still can’t. Please fix my code.

My code:

public static void deslocaMaiorFinal(int[] Arranjo){
    int maior = Arranjo[0];
    int aux;
    for(int c = 1; c < Arranjo.length; c++){
        if(Arranjo[c] > maior) maior = Arranjo[c];
    }//end for

    for(int c = (Arranjo.length - 1); c >= 0; c--){
        if(Arranjo[Arranjo.length-1] != maior){
            aux = Arranjo[c];
            Arranjo[c] = maior;
            Arranjo[c-1] = aux;
        }//end if
    }//end for
    return;
}//end method

1 answer

0

You don’t need the second part:

for(int c = (Arranjo.length - 1); c >= 0; c--){
   if(Arranjo[Arranjo.length-1] != maior){
       aux = Arranjo[c];
       Arranjo[c] = maior;
       Arranjo[c-1] = aux;
   }//end if
}//end for

If you have already identified the highest value (as you did in the first part) just assign to the last position.

Arranjo[Arranjo.length-1] = maior;
  • Now, if you want to sort the array, there’s something else.

  • Yeah, I want to order so the big one gets last.

Browser other questions tagged

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