Placing a vector in descending order

3

I need to create a vector of size N but it has to be ordered decreasing only when I make the code always 0.

public int[] vetor_dec (int n) { 
    int[]vetor = new int[n];
    for(int i=n;i>vetor.length;i--) {
        int aux=0;
        vetor[aux]=i;
        aux++; 
    } 
    return vetor;
} 

Would you tell me what's wrong?

    
asked by anonymous 17.09.2014 / 15:15

3 answers

4

I quickly looked at his int aux=0; is inside For , he is always feeding his vector in position 0!

    
17.09.2014 / 15:28
4

The problems in your code are as follows:

  • You'll never get into this loop:

    for(int i=n;i>vetor.length;i--) {
    

    At start, i is n , which is equal to vetor.length ; when the condition is tested, will give false face, so that it will return the unchanged vector.

    And as in Java a vector is always started with everything zero (or null , if it's a reference vector) then that's what you get.

    One solution is to go from n to 1 :

    for(int i=n;i>0;i--) {
    
  • aux is being defined within the body of the loop

    for(int i=n;i>vetor.length;i--) {
        int aux=0;
    

    This means that even if your first problem is solved, it will always be zero. This would cause you to assign the zero position of your vector several times (one overwriting the other). The result would be something like:

    {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    

    To solve this, just move the aux out of the loop, so that it preserves its value (incremented by you) between one iteration and another:

    int aux=0;
    for(int i=n;i>vetor.length;i--) {
    
  • Complete code:

    int[]vetor = new int[n];
    int aux=0;
    for(int i=n;i>0;i--) {
        vetor[aux]=i;
        aux++; 
    } 
    return vetor;
    

    Note: I'm assuming you want values from 1 to n . If you want another range - for example from 0 to n-1 - adjust the condition of your for accordingly.

        
    17.09.2014 / 15:46
    3

    Change your for and strip the aux variable from the loop. Leave the code like this:

    public int[] vetor_dec (int n) { 
        int[]vetor = new int[n];
        for(int i=n-1;i>=0;i--) {
            vetor[i]=i+1; 
        } 
        return vetor;
    } 
    
        
    17.09.2014 / 15:25