I am stuck and a simple yet crazy search algorithm. I want to find the index of an element from an array calling a function. The problem is that although the element is already there, the function returns -1; which is supposed to return only if the element is not there. This is the code:
#include <iostream>
using namespace std;
int search(int arr[], int size, int val, bool left) {
int res;
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
else if(val != arr[i]) {
res = -1;
}
}
return -1;
}
int main() {
int arr[] = {1, 4, 6, 5, 2, 7, 10, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << search(arr,size,6, true) << endl;
return 0;
}
Thanks in advance.