Here is a C function
Note that the Binary Search algorithm has a prerequisite that the array passed to it must be already sorted in ascending order. This will not work on an unsorted array. Thecomplexity of this algorithm is O(log(n)).
Code
int binarySearch(int arr[],int size, int item)
{
int left, right, middle;
left = 0;
right = size-1;
while(left<=right)
{
middle = ((left + right)/2);
if(item == arr[middle])
{
94
return(middle);
}
if(item > arr[middle])
{
left = middle+1;
}
else
{
right = middle-1;
}
}
return(-1);
}
{
int left, right, middle;
left = 0;
right = size-1;
while(left<=right)
{
middle = ((left + right)/2);
if(item == arr[middle])
{
94
return(middle);
}
if(item > arr[middle])
{
left = middle+1;
}
else
{
right = middle-1;
}
}
return(-1);
}
Note that the Binary Search algorithm has a prerequisite that the array passed to it must be already sorted in ascending order. This will not work on an unsorted array. Thecomplexity of this algorithm is O(log(n)).
No comments:
Post a Comment