-2
Good afternoon!
I’m very lost in this matter of a college job because I didn’t understand right recursion. Could someone help me?
I need it here: A function that returns the index in which the searched element is found or -1 if the element is not present. It takes, as an argument, the array of integers, the beginning and end of the interval analyzed at each recursion, and the value to be searched for.
My code is like this so far (basically I took it off the internet because I didn’t know where to start)
#include <stdio.h>
#define TAMANHO 6
int bin_search (int *v, int begin, int end, int value){
int i = (begin + end)/2; //meio do vetor
if (begin > end){
return -1; //se o inicio for maior que o fim > -1 (não é decrescente)
}
if (v[i] == value){ //vetor do meio = valor?
return i;
}
if(v[i] < value){ //se o valor for maior que o vetor do meio = fim do vetor
return bin_search(v, i+1,end,value);
}
else if (v[i] > value) { //se o valor de i for maior que valor = inicio do vetor.
return bin_search(v, begin, i-1,value);
}
}
int main (){
int v [TAMANHO] = {1, 3, 5, 10, 20, 30};
int i,begin,end;
for(i = 0; i < TAMANHO; i++){
int value = v[i];
printf("Busca binaria recursiva: %d\n",value,bin_search(v,0,TAMANHO -1, value));
}
}
How do I return the start and the end? Data entry is also a little complicated for me.
Thanks since already <3