0% found this document useful (0 votes)
19 views2 pages

Bsearch

The document contains a C program that implements a binary search algorithm to find the position of a specified value in a sorted array. It defines a recursive function 'binarySearch' to search for the value and a 'main' function to initialize the array, call the search function, and display the results. The program outputs the elements of the array and indicates whether the searched element is present, along with its position if found.

Uploaded by

shivgovindvns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views2 pages

Bsearch

The document contains a C program that implements a binary search algorithm to find the position of a specified value in a sorted array. It defines a recursive function 'binarySearch' to search for the value and a 'main' function to initialize the array, call the search function, and display the results. The program outputs the elements of the array and indicates whether the searched element is present, along with its position if found.

Uploaded by

shivgovindvns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <conio.h>
int binarySearch(int a[], int beg, int end, int val)

int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than middle, then it
can only be in left subarray */
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle, then it
can only be in right subarray */
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
void main()
{
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70};
int val = 40, i;
clrscr();
int n = sizeof(a) / sizeof(a[0]);
int res = binarySearch(a, 0, n-1, val);
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
getch();
}

You might also like