Hi all Please help me to solve this problem. i tried to solve this problem many times. but i couldnt do that. so please look at my code & help me to code this correctly. thanks Write a C++ program that will call a function that performs Binary Search on a sorted array. [You could use the binary search function provided in the class notes for this task.] The value to be searched for is: 12.5 float array2 = { 2.3, 4.8, 5.1, 6.8, 7.6, 8.3, 10.2, 11.4, 12.5, 18.9, 27.3 } The code need to correct Code: Code: #include <iostream.h> #include <conio.h> int main() { float a[]={2.3,4.8,5.1,6.8,7.6,8.3,10.2,11.4,12.5,18.9,27.3}; float item=12.5; int middle; int lv=1,hv=11; for(int i=0;a[middle]!=item;i++) { middle = (lv + hv)/2; if(a[middle]>item) hv = middle - 1; else if(a[middle]<item) lv = middle + 1; else if(a[middle]==item) cout<<"Found your number in "<<middle+1<<" position."; } getch(); }
try setting middle to ZERO...int middle=0; otherwise a[middle] is taking some arbitary position as there is no bound checking
You've forgotten C counts from zero. The code looks at a[11], which doesn't exist (27.3 is a[10]), and completely ignores a[0]. I don't see the point of "i". Why not just use while(a[middle]!=item)? Also the code doesn't call a function as required by the task notes. It does everything in main().
Hello....in my computer the binary search is running absolutely perfect.....here, have a look at my algorithm..... Code: #include<stdio.h> #include<conio.h> float binsearch(float a[], float n, float x) { int L, R, M; L=0; R=n-1; while(L<R) { M=(L+R)/2; if(x>a[M]) L=M+1; else R=M; } return(a[L]==x?1:0); } void main() { float a[]={2.3,4.8,5.1,6.8,7.6,8.3,10.2,11.4,12.5,18.9,27.3}; float x; float n=11; printf("Enter your x="); scanf("%f", &x); if(binsearch(a,n,x)==1) printf("......FOUND......"); else printf("......NOT FOUND......"); getch(); } Hope it is allright....cheers..... --------------- @ r K @
You can also run it using Code: int n; instead of Code: float n; .....I checked it right now... ---------------- @ r k @