Monday, 2 February 2015

Binary Search program in C

Friends,

Below are the binary search programs written in C. One is recursive version and the other is iterative version. I'll keep updating all algorithms as C codes.


Programs are simple and self explanatory.


ITERATIVE BINARY SEARCH



#include<stdio.h>

int BinSrch(int arr[],int low_index, int up_index, int key)
{
int mid;
while(low_index <= up_index)
{
mid = (low_index + up_index)/2;
if(key < arr[mid])
{
up_index = mid-1;
}

else if(key > arr[mid])
{
low_index = mid + 1;
}
else
return mid;
}
return -1;
}

int main()
{
printf("\nEnter no of elements: ");
int n;
scanf("%d",&n);
int arr[n],i;

printf("\nEnter elements: ");
for(i=0;i {
scanf("%d",&arr[i]);
}

printf("\nEnter search element: ");
int key;
scanf("%d",&key);

int position = BinSrch(arr,0,n-1,key);
if(position == -1)
printf("\nElement not found!");
else
printf("\nElement found at position: %d",position);
return 0;
}







RECURSIVE BINARY SEARCH

#include<stdio.h>

int BinSearch(int arr[], int low_index, int up_index, int key)
{
if(low_index <= up_index)
{
int mid = (low_index + up_index)/2;

if(key < arr[mid])
return BinSearch(arr,low_index,mid-1,key);

else if(key > arr[mid])
return BinSearch(arr,mid+1,up_index,key);

else
{
return mid;
}
}

else
{
return -1;
}
}//BinSrch()


int main()
{
int n,i;
printf("\nEnter no of elements: ");
scanf("%d",&n);
int arr[n];
printf("\nEnter elements: ");
for(i=0;i scanf("%d", &arr[i]);
printf("\nEnter search element: ");
int key;
scanf("%d", &key);
int position = BinSearch(arr,0,n-1,key);
if(position == -1)
printf("\nSearch element not found!!");
else
printf("\nSearch element found at position %d",position);
return 0;
}




No comments:

Post a Comment