c - How can I make this recursive Binary Search program exit and not crash if the number is not found? -
c - How can I make this recursive Binary Search program exit and not crash if the number is not found? -
how can prevent programme crashing if value user searched not found? (when seek implement if/else or count system, programme doesn't work correctly)
#include <stdio.h> #include "simpio.h" #include "genlib.h" #define start 0 void bubble(int numbers[]); int binary(int val, int numbers[], int low, int high); void io(int numbers[]); int size; main() { int result, search; printf("this programme sorts , searches array\n"); printf("how many numbers sort , search?\n"); size = getinteger()-1; int numbers[size]; printf("enter numbers\n"); io(numbers); bubble(numbers); printf("which number search for?\n"); search = getinteger(); result = binary(search,numbers,start,size); printf("the number %d found @ index %d\n",search,result+1); } void io(int numbers[]) { int ink; for(ink=0;ink<=size;ink++) { numbers[ink] = getinteger(); } } void bubble(int numbers[]) { int first,second,count,swap; while(true) { for(first=0,second=1,count=0;second<=size;first++,second++) { if(numbers[first]>numbers[second]) { count++; swap = numbers[first]; numbers[first]= numbers[second]; numbers[second] = swap; } } if(count==0)break; } } int binary(int val, int numbers[], int low, int high) { int mid; mid = (low+high)/2; if(val==numbers[mid]||low>high) homecoming mid; if(val>numbers[mid]) return(binary(val,numbers,mid,high)); else if(val<numbers[mid]) return(binary(val,numbers,low,mid)); }
change to
size = getinteger(); int numbers[size--];//change size max index //.. int binary(int val, int numbers[], int low, int high) { int mid; if(low>high)//if not found! homecoming -1;//check homecoming value @ main mid = (low+high)/2; if(val==numbers[mid]) homecoming mid; if(val>numbers[mid]) return(binary(val,numbers,mid+1,high)); else if(val<numbers[mid]) return(binary(val,numbers,low,mid-1)); }
c recursion crash binary-search
Comments
Post a Comment