Consider a binary search. Its algorithm will be presented, as well as an example of a program that implements the search for an element in an array. We will develop the development in the C programming language.

So, the idea of binary search is as follows: the element sought is compared with the middle element of the sequence. If the value of the search argument is less than the average element, then the initial sequence is an array of elements from 1 to N/2, if the value of the search argument is greater than the average element, then the initial sequence is considered to be a sequence from N/2 to N. Next, for a new sequence, this process is repeated. Continue dividing the search interval into halves until the searched item is found or the length of the search interval becomes one.

We present the implementation of the algorithm in C language. The function int binary search (int a, int mass [], int n) takes as arguments: the element to be searched, a pointer to an array of elements, and the number of elements in this array. In the case of a successful search, binary search returns the position of the searched item in the array, if the search argument is not present in the element sequence, then the function returns -1.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include<stdio.h> #include<conio.h> void main() { int a[100],i,n,x,f,l,m,flag=0; clrscr(); printf("enter how many value in array\n"); scanf("%d",&n); printf("Enter %d value in ascending order\n",n); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Which value to be search ->"); scanf("%d",&x); /* Binary Search logic */ f=0;l=n-1; while(f<=l) { m=(f+l)/2; if(x==a[m]) { flag=1; break; } else if(x<a[m]) l=m-1; else f=m+1; } if(flag==0) printf("%d value not found\n",x); else printf("%d value found at location %d\n",x,m); getch(); } |