0
I have the following question:
Develop a recursive function that finds a value in an ordered vector using binary search. The function must respond to the position of the vector value. 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 solve this problem?
Post code as text even to make it easier for people to help.
– Maniero
Read this: http://meta.pt.stackoverflow.com/q/5149/132
– Victor Stafusa
Remember that in C arrays start at position 0, not position 1.
– Victor Stafusa
Ah, website formatting recognizes lines starting from 4 spaces as source code. So put 4 spaces at the beginning of each line of your code and post. Another alternative is to post your entire code, select it and then click the button
{}
that appears in your edit bar.– Victor Stafusa