I have the following question:
Develop a recursive function that finds a value in an ordered vector using binary search. The function must give the position of the vector value as a response. If the value is not in the vector, it returns -1.
Then I developed the following:
#include <stdio.h>
#include <stdlib.h>
int BuscaBinaria(int[] v, int inicio, int fim, int valor) {
int meio;
meio=(inicio+fim)/2;
if(meio>valor)
{
return BuscaBinaria(v, inicio, meio-1, valor);
}
if(meio<valor)
{
return BuscaBinaria(v, inicio+1, meio, valor);
}
if(meio==valor)
{
return meio;
}
else {
return -1;
}
}
int main()
{
int tam, valor;
int k;
printf("Qual o tamanho do vetor: ");
scanf("%d", &tam);
int v[tam], i;
printf("Informe os valores do vetor:\n");
for(i=1; i<=tam; i++)
{
scanf("%d", &v[i]);
}
printf("Informe o numero a ser buscado: ");
scanf("%d", &valor);
k= BuscaBinaria(v,1,tam,valor);
printf("%d", k);
}
But when the value is not inside the vector, the program gives error. It stops and returns any number at the end. How can I resolve this problem?