Below code finds the desired key in array and prints it but when key is not found, I expect the search return -1 and print "Key not found." But this is not printed. Is there a mistake?
#include<stdio.h>
int binarySearch(int* arr, int size, int key){
int low=0;
int high=size-1;
int mid=(low+high)/2;
while(arr[mid]!=key){
if(key>arr[mid]){
low=mid+1;
mid=(low+high)/2;
}
if(key<arr[mid]){
low=0;
high=mid-1;
mid=(low+high)/2;
}
if(key==arr[mid]){
return mid;
}
}
}
int main(){
int intArr[10]={4,5,12,44,232,326,654,776,987,999};
int res=binarySearch(intArr, 10, 1);
if(res){
printf("Key found at index: %d.", res);
}else ("Key not found.");
}
Note: I made a mistake on syntax of this part. I corrected.
this
else ("Key not found.");
to
else (printf("Key not found.\n"));
It is working as intended after this correction. I also added @weatherwane' s suggestion and @poepew's suggestions.
Here is the working code:
#include<stdio.h>
int binarySearch(int* arr, int size, int key){
int low=0;
int high=size-1;
int mid=(low+high)/2;
while(high-low>0){
if(key>arr[mid]){
low=mid+1;
mid=(low+high)/2;
}
if(key<arr[mid]){
low=0;
high=mid-1;
mid=(low+high)/2;
}
if(key==arr[mid]){
return mid;
}
}
return -1;
}
int main(){
int intArr[10]={4,5,12,44,232,326,654,776,987,999};
int res=binarySearch(intArr, 10, 43);
if(res>=0){
printf("Key found at index: %d.\n", res);
}
else (printf("Key not found.\n"));
}