Program:-
#include <stdio.h>
int bsearch(int array[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (array[mid] == x)
return mid;
if (array[mid] > x)
return bsearch(array, l, mid-1, x);
return bsearch(array, mid+1, r, x);
}
return -1;
}
int main()
{
int array[] = {2, 3, 4, 10, 40,15,34};
int n = sizeof(array)/ sizeof(array[0]);
int x = 10;
int result = bsearch(array, 0, n-1, x);
(result == -1)? printf("Element is not present in arrayay")
: printf("Element is present at index %d",
result);
return 0;
}
BINARY SEARCH ITERATIVE:-
#include <stdio.h>
int bsearch(int array[], int l, int r, int x)
{
while (l <= r)
{
int m = l + (r-l)/2;
if (array[m] == x)
return m;
if (array[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
int main()
{
int array[] = {12, 30, 4, 10, 40,78,12};
int n = sizeof(array)/ sizeof(array[0]);
int x = 10;
int result = bsearch(array, 0, n-1, x);
(result == -1)? printf("Element is not present"
" in arrayay")
: printf("Element is present at "
"index %d", result);
return 0;
}
No comments:
Post a Comment