0

What am I doing wrong ???

//binary search int main() { int A[N],l,initial,final,mid ,data ; cout << "Enter ten values in ascending order"; for (l = 0; l < N; l++) cin >> A[l]; cout << "Enter data to be searched"; cin >> data; initial = 0; final = N - 1; mid = (initial + final) /2; while (initial < = final) && (A[mid]! = data)) { if (A[mid] > data) final = mid - 1; else initial = mid + 1;) } if (A [mid] == data) cout <<"data is present"; if (initial > final) cout << "data not present

20th Oct 2016, 7:32 AM
kevink mahadeo
kevink mahadeo - avatar
4 Respostas
+ 2
mid is equal to 9/2 which is 4.5, but you have declared mid as an int, so the compiler is going to discard any remainder after the decimal, leaving you with just 4. at leat with N being 10 or any even number, because final is equal to N - 1. also, right after the while, there's a parentheses missing, but the parentheses around the conditional statements are unnecessary. if what you're trying to do here is search the array for what the user inputs, I'd suggest using: for (int i = 0; i < N; i++) { if (A[i] == data) cout << "data present" << endll; else cout << "data not present" << endl; }
21st Oct 2016, 5:53 AM
Zeke Williams
Zeke Williams - avatar
0
Be careful with the for(), while() and if syntaxes. Put the code into the { }
20th Oct 2016, 12:36 PM
Geoffrey
Geoffrey - avatar
0
Thanks u
21st Oct 2016, 6:20 AM
kevink mahadeo
kevink mahadeo - avatar
0
Also, in your original post mid is never modified in the loop, so A[mid] is always the same
21st Oct 2016, 8:50 AM
qwertyuiof