Binary search in Data structure by R4R Team

Array:
Array is the collection of different values having same data type.
-We have a integer Array that having all integer values.
-Character array is known as String.

Searching in Array:
Possible Search in Array is
1. Linear search
2. Binary search

Binary search:
It is used to find the element in the array.
-Applicable only on Sorted data.

program-

#include < stdio.h>
int main()
{
int i,first=0, last, middle,n, num, arr[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d elements in array\n", n);
//Input in array
for(i= 0;i< n;i++)
scanf("%d",&arr[i]);
printf("Enter value to find\n");
scanf("%d", &num);
last = n - 1;
middle = (first+last)/2;
while(first<=last) {
if(arr[middle]< num)
first = middle + 1;
else if (arr[middle]==num) {
printf("%d found at location %d\n",num, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list\n", num);
return 0;
}


output-

Enter number of elements
6
Enter 6 elements in array
1 2 3 4 5
Enter value to find
2
2 found at location 2




Leave a Comment:
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!