Binary Search in C Program Using Function

Binary search in c program using function. In this program, we can execute the binary search algorithm for beginners to implement in c using functions.

Binary Search Definition in C

Binary search, also known as half-interval search, logarithmic search, or binary chop in computer science, is a search technique that locates a target value within a sorted array. 

The target value is compared to the array’s middle element in a binary search. Binary Search is a search algorithm for locating a certain element (target value) in a sorted array. 

Prior to doing a binary search, the array should be sorted. Logarithmic search, binary chop, and half interval search are all terms used to describe binary search.

Function Definition in C

A function is a collection of statements that work together to complete a task. Every C program contains at least one function, main(), and even the simplest programs can specify more functions. 

The name, return type, and parameters of a function are all specified in a function declaration. A function is a logical unit of code that is frequently defined by its place in a larger code structure. 

A function is a unit of code that works on a variety of inputs, many of which are variables, and produces concrete results such as changing variable values or performing actual operations based on the inputs.

Binary Search in C Program Using Function

#include<stdio.h>
int func(int array[], int x, int low, int high) 
{
while (low <= high) 
{
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) 
{
int array[] = {5, 3, 5 ,9, 1, 2, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 5;
int result = func(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element Is In The Array %d", result);
return 0;
}

Output:

Element Is In The Array 2