Recursive analysis of a vector

7

QUESTION:

Write a recursive function that parses the elements of a vector and returns one of the following codes:

0 Disordered elements
1 Items sorted in ascending order
2 Constant elements
3 Items ordered in descending order

int AnalisaVetor(int V[], int n);

Use the above prototype where "n" indicates the number of elements present in the array.

Examples:

Para V={1,2,2,5,6,6,7,8,8,9} retorna código 1.
Para V={20,15,11,10,8,8,5,2} retorna código 3.
Para V={1,20,2,5,6,6,7,80,9} retorna código 0.
Para V={8,8,8,8,8,8,8,8,8,8} retorna código 2.

Attempting to resolve the issue I came up with the following code:

int analisa(int v[], int n)
{
    if(v[n-1] == v[n-2])
    {
        if(n == 2)
        {
            return 2;
        }
        else
        {
            return analisa(v, n-1);
        }
    }
    else if(v[n-1] < v[n-2])
    {
        if(n == 2)
        {
            return 3;
        }
        else
        {
            return analisa(v, n-1);
        }
    }
    else if(v[n-1] > v[n-2])
    {
        if(n==2)
        {
            return 1;
        }
        else
        {
            return analisa(v, n-1);
        }
    }

    return 0;

}

However, it does not work as expected when, for example, the first two elements of the vector are the same and the rest follow a growing or decreasing sequence. Another case in which there is no expected operation is when the vector is disordered. How can I fix these errors?

    
asked by anonymous 04.10.2015 / 15:37

1 answer

9

Your conditions are incomplete.

An array of N elements is composed of increasing numbers when the smallest array with the first N - 1 is composed of increasing numbers and the next-to-last array element is not greater than the last one . In other words,

// chamar função com array de 0 elementos é Comportamento Não Definido
int analisa(int *v, size_t n) {
    if (n == 1) return 2; // um array com um elemento é "constante"
    int tmp = analisa(v, n - 1); // analisa array mais pequeno recursivamente
    switch (tmp) {
        case 0: // array mais pequeno desordenado
            return 0;
            break;
        case 1: // array mais pequeno crescente
            if (v[n - 2] > v[n - 1]) return 0; // desordenado
            return 1;
            break;
        case 2: // array mais pequeno constante
            if (v[n - 2] < v[n - 1]) return 1; // crescente
            if (v[n - 2] > v[n - 1]) return 3; // decrescente
            return 2;
            break;
        case 3: // array mais pequeno decrescente
            if (v[n - 2] < v[n - 1]) return 0; // desordenado
            return 3;
            break;
        default: // erro
            return -1; // erro
            break;
    }
}
    
05.10.2015 / 16:34