#include<stdio.h>
int main() {
/* For binary search, the array should be arranged in ascending or descending order */
int data[] = {1,2,3,4,5,6,7,8,9,10}; ****You might change the numbers for your program also
/* 'min' use for starting location of the array, 'max' use for end location of the array and 'mid' use for middle location of the array */
int min = 0, max = 10, search, mid = (max + min) / 2;
printf("Enter a number to search:\n");
scanf("%d", &search);
while(min <= max) {
****** INSERT YOUR CODE TO COMPLETE THE PROGRAM ******
}
if(min > max)
printf("%d is not found!\n",search);
return 0;
}
Looking for alternative solutions for this program code.
#include<stdio.h>
int main()
{
//Binary Search (Considering Ascending Order of Elements in the Array)
int data[] = {1,2,3,4,5,6,7,8,9,10};
//min, mid and max variables to indicate starting, middle and ending index (or position) of the array respectively
int min = 0, max = 10, search, mid = (max + min) / 2;
printf("Enter a number to search:\n");
scanf("%d", &search);
while(min <= max) {
//If the element is greater than mid value, then mid
becomes the min
if(data[mid]<search)
min=mid+1;
//If element is found in the middle
else if(data[mid]==search)
{
printf("%d is found at index:
%d",search,mid);
break;
}
//If the element is smaller than
mid, then mid becomes the max
else
max=mid-1;
//Updating the mid position
mid= (max+min)/2;
}
//If the element is not found in the
array
if(min > max)
printf("%d is not found!\n",search);
return 0;
}
Sample Outputs:
Recursive Approach:
#include<stdio.h>
//bSearch() function to perform binary search with an array,
min-index, max-index, search element as parameters
int bSearch(int arr[],int min,int max,int search)
{
//variable to store mid positon
int mid;
if(min<=max)
{
mid = (min+max)/2;
//If the element is found at mid
position, then return the positon.
if(arr[mid]==search)
return
mid;
//If the search element is less
than the mid value, then max=mid-1 and call
bSearch()
else if(search<arr[mid])
return
bSearch(arr,min,mid-1,search);
//If the search element is greater
than the mid value, then min=mid+1 and call
bSearch()
else
return
bSearch(arr,mid+1,max,search);
}
//If the element is not found
return -1;
}
void main()
{
int arr[]={10,20,33,45,49,65,77,81,94,101};
int result,search;
printf("Enter a number to search:\n");
scanf("%d", &search);
result=bSearch(arr,0,10,search);
if (result==-1)
printf("%d is not
found",search);
else
printf("%d is found at index:
%d",search,result);
}
Sample Runs:
Get Answers For Free
Most questions answered within 1 hours.