6
QUESTION:
Write a function recursive that analyzes the elements of a vector and returns one of the following codes:
0 Disordered elements
1 Elements sorted in ascending order
2 Constant elements
3 Items sorted in descending order
int AnalisaVetor(int V[], int n);
Use the above prototype where "n" indicates the number of elements present in the vector.
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.
Trying to resolve the issue I arrived at 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 in an expected way when, for example, the first two elements of the vector are equal and the rest follow a ascending or descending sequence. Another case in which there is no expected functioning is when the vector is disordered. How can I correct these errors?
Does the algorithm need to be recursive (does the exercise ask for this?) or do you think recursion is a good way out? If the exercise asks for the use of recursion, ok, but if it does not ask, it is better not to use.
– user21742
The exercise calls for this.
– Vinicius