Need a help in binary search problm. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Need a help in binary search problm.

I want output in floating point am getting lots of error anyone can help to fixup https://code.sololearn.com/cEn9d4U023rN/?ref=app

5th Apr 2021, 6:16 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
3 Answers
+ 3
There appears to be many problems. Here is a fixed version: #include <stdio.h> float * search_dicho(float v, float *tab, int size) { int milieu; if (size <= 0) return NULL; // indicate nothing found. milieu=size/2; if (tab[milieu]==v) { return tab + milieu; // found } else if(tab[milieu]<v) { return search_dicho(v, tab + milieu + 1, size - milieu - 1); } else { return search_dicho(v, tab, milieu); } } void sort(float *tab, int size) { int i,j,temp; for (i=0; i<size; i++) { for (j=i+1; j<size; j++) { if (tab[i] > tab[j]) { temp=tab[i]; tab[i]=tab[j]; tab[j]=temp; } } } } int main() { float tab[10],key; float * flag; int i; int size=10; for(i=0;i<10;i++) { printf("\nENTER NUMBER-%d: ",i+1); scanf("%f",&tab[i]); } sort(tab, size); printf("\nTHE SORTED ARRAY IS:\n"); for (i=0; i<10; i++) printf("%f ",tab[i]); printf("\nENTER A NUMBER TO SEARCH: "); scanf("%f",&key); flag=search_dicho(key,tab,size); if(flag != NULL) printf("\nTHE NUMBER %f EXISTS", key); else printf("\nTHE NUMBER %f DOES NOT EXIST ARRAY", key); return 0; } A few changes are: - made indents consistent - replaced global size variable with local size variables and parameters - made search_dicho return address of found float or NULL if not found. The caller checked if flag == 1 which was weird when data type was float *. - search_dicho(v,&tab,size) wasn't the right data type for the tab variable. Fixed that. - fixed parameters in search_dicho to search either side of milieu correctly. - removed unused variables
5th Apr 2021, 8:02 PM
Josh Greig
Josh Greig - avatar
+ 2
For better indentation, check the above example or the Linux style from: https://www.gnu.org/software/indent/manual/indent.html
5th Apr 2021, 8:32 PM
Josh Greig
Josh Greig - avatar
+ 1
Martin Taylor Josh Greig thankyou sir thanks a lot
6th Apr 2021, 4:16 AM
A S Raghuvanshi
A S Raghuvanshi - avatar