0% found this document useful (0 votes)
27 views

Binary Search in Arra

This document describes and provides an example of binary search in an array. It defines a function called bsearch that takes an array, size, and item to search for as parameters. The function initializes begin and last indexes and uses a while loop to repeatedly calculate the mid-point of the array section. It compares the item to the mid-point value and updates begin or last index based on if the item is lower or higher. It returns the index if found, or -1 if not found. Main calls bsearch to search an array of integers for a user-input value and prints the result.

Uploaded by

ravi_5227
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Binary Search in Arra

This document describes and provides an example of binary search in an array. It defines a function called bsearch that takes an array, size, and item to search for as parameters. The function initializes begin and last indexes and uses a while loop to repeatedly calculate the mid-point of the array section. It compares the item to the mid-point value and updates begin or last index based on if the item is lower or higher. It returns the index if found, or -1 if not found. Main calls bsearch to search an array of integers for a user-input value and prints the result.

Uploaded by

ravi_5227
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

BINARY SEARCH IN ARRAY

#include<conio.h>
#include<stdio.h>
int bsearch(in tar[i],int size,int item) //function to perform binary search
{
int beg, last,mid;
beg=0;
last=size-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==ar[mid])
return mid;
else if(item>ar[mid])
beg=mid+1;
else
last=mid-1;
}
return -1; //the control will reach here only if the item is not found
}

void main()
{
in tar[50],item,n,index;
clrscr();
printf(“\n ENTER DESIRED ARRAY SIZE(MAX 50)-:”);
scanf(“%d”,&n);
printf(“\n ENTER ARRAY ELEMENTS(must be in acs order)-:\n”);
for(int i=0;i<n;i++)
{
scanf(“%d”,ar[i]);
}
printf(“\n ENTER ELEMENT TO BE SEARCHED FOR-:”);
scanf(“%d”,&item);
index=bsearch(ar,n,item);
if(index==-1)
printf(“\n SORRY!GIVEN ELEMENT COULD NOT BE FOUND.\n”);
else
printf(“\n ELEMENT FOUND AT INDEX %d POSITION %d”,index,(index+1));

getch();
}

OUTPUT
ENTER DESIRED ARRAY SIZE(MAX 50)-:7
ENTER ARRAY ELEMENTS(must be in acs order )- :
2 5 7 8 9 10 15
ENTER ELEMENT TO BE SEARCHED FOR-:8
ELEMENT FOUNT AT INDEX :3, POSITION :4

You might also like