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.
printf("enter how many value in array\n");
printf("Enter %d value in ascending order\n",n);
printf("Which value to be search ->");
/* Binary Search logic */
printf("%d value not found\n",x);
printf("%d value found at location %d\n",x,m);