Placing a vector in decreasing order

Asked

Viewed 99 times

3

I need to create a vector of size N but it has to be ordered down only when I do the code always from 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;
} 

You could tell me what’s wrong?

3 answers

4


I looked quickly here yours int aux=0; this inside the For, is feeding its vector always at position 0 !

4

The problems with your code are as follows::

  1. You’ll never get into that loop:

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

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

    And how in Java an array is always started with everything zero (or null, if it’s a reference vector) then that’s what you’ll get.

    One solution is to travel from n until 1:

    for(int i=n;i>0;i--) {
    
  2. The aux is being set inside 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 1 to n. If you want another interval - for example 0 to n-1 - adjust the condition of your for accordingly.

3

Changes your for and takes out the variable aux of 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;
} 

Browser other questions tagged

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