Wednesday, 7 September 2016

Recursive Binary Search

Binary Search Using Recursion

#include<stdio.h>

void binary_search(int a[100], int low, int high, int key)
{
                int mid;
                if(low>high)
                {
                                printf("\nKey not found");
                                return;
                }
                mid = (low+high)/2;
                if(key == a[mid])
                {
                                printf("\nKey element is found at position = %d", mid);
                }
                else  if(key<a[mid])
                                binary_search(a, low, mid-1, key);
                else
                                binary_search(a, mid+1, high, key);
}
void main()
{
                int a[100], i, n, pos, key;
                printf("\nEnter value of n: ");
                scanf("%d", &n);
                printf("\nEnter the array elements: ");
                for(i=0; i<n; i++)
                                scanf("%d", &a[i]);

                printf("\nEnter key: ");
                scanf("%d", &key);
                binary_search(a, 0, n-1, key);
}

Output:
Enter value of n: 6
Enter the array elements: 11 22 33 44 55 66
Enter key: 55
Key element is found at position = 5


Enter value of n: 6
Enter the array elements: 11 22 33 44 55 66
Enter key: 88
Key is not found