Monday, 26 February 2018

Binary search algorithm implementation using C program

Binary search algorithm implementation using C program

Program:


/* recursive binary search*/
#include<stdio.h>

int bsearch(int [ ],int, int, int); //function declaration

int main( )
{
int a[20], i, low_index, high_index;
int position, total_keys, key_to_find
printf("\nEnter the total number of values:");
scanf("%d", &total_keys);

for(i = 0; i < total_keys; i++)
{
    printf("\nEnter the key elements %d  : ", i);
    scanf("%d", &a[i]);
}
printf("\nEnter the key to search : ");
scanf("%d", &key_to_find);
low_index = 0;
high_index = n-1;
//the following line calls the function bsearch with parameters
position = bsearch(a, key_to_find, low_index, high_index);
if(position!=-1)
    printf("Search successful, element found at position %d", position);
else
    printf("Search unsuccessful, element not found");
getch();
}

int bsearch(int a[ ], int k, int lb, int ub)
{
int mid;
while(ub >= lb) //repeat this loop while upper bound >= lower bound
             {
             mid=(lb+ub)/2; //finds new middle index in each iteration
             if(k < a[mid]) //if the key_to_find is smaller than middle element of array,
                  ub = mid-1; //set the new upper bound as middle-1
             else if(k > a[mid]) //if key_to_find is larger than middle
                  lb = mid+1; //set the new lower bound as middle+1
             else if(k == a[mid]) //if key_to_find is equal to middle element
                  return(mid); //return the middle element as result
             return (bsearch(a,k,lb,ub)); //if none of the above holds, call bsearch (recursive)
}
return -1; //if the key_to_find is not in the list, return -1 to tell ‘NOT FOUND’
}

**************




binary search program in C
binary search algorithm using recursive functions in C
binary search divide and conquer algorithm
binary search simple program in C
 





No comments:

Post a Comment

SQL exercises for beginners one

SQL Exercises for Beginners / Simple SQL Exercises with Answers / Solved SQL exercises / SQL solved exercises with simple conditions / So...