You are on page 1of 5

Aim:

To write a program to search an element in array by using binary search recursive


method.

Description:
• Sequential search algorithm is very slow if list contains more number of elements.
• If the array is not sorted ,linear search is the only solution.
• If the list is sorted , we can use a more efficient algorithm called the binary search.
• We should use a binary search whenever the list starts to become large.
• The binary search starts by testing the data in the element at the middle of the list.
• This determines if the target is in first half or second half of the list.
• If it is in first half , we do not need to check the second half.
• If it is in second half , we do not need to check the first half.
• In other words ,either way we eliminate half the list from further consideration.
• We repeat this process until we find the target or satisfy ourselves that it is not in the list.
• To find the middle of the list we three variables,
one to identify the beginning of the list(first)
one to identify the beginning of the list(mid)
one to identify the beginning of the list(last)
mid=( first + last )/2

Step by Step Procedure:


#include <stdio.h>
int Recursivebinary_search(int a[] , int low , int high , int key)
{
if(low > high)
{
return -1;
}
int mid = ( low + high) / 2;
if ( a[mid] == key)
{
return mid;
}
else if(key < a[mid])
{
Recursivebinary_search(a , low , mid-1 , key);
}
else
Recursivebinary_search(a , mid+1 , high , key);
}
int main()
{
int a[] = { 3,6,8,10,14,15,20,30,66,99 };
int digit;
printf("enter the digit\n");
scanf("%d",&digit);
printf("digit is at %d\n",Recursivebinary_search(a, 0 , 9 , digit));
return 0;
}
ARRAY = { 3,6,8,10,14,15,20,30,66,99 }

CASE-1: key element = 6


Iteration-1: low = 0 ; high = 9 ; mid = 4
a[4] = 14
Key < a[4]

Iteration-2: low = 0 ; high = 4 ; mid = 2


a[2] = 8
Key < a[2]

Iteration-3: low = 0 ; high = 2 ; mid = 1


a[1] = 6
Key < a[1]
Key element is found at position 1

CASE-2: key element = 14


Iteration-1: low = 0 ; high = 9 ; mid = 1
a[4] = 14
Key = 14
Key element is found at position 1
CASE-3: key element = 99
Iteration-1: low = 0 ; high = 9 ; mid = 4
a[4] = 14
Key > a[4]

Iteration-2: low = 9 ; high = 2 ; mid = 7


a[7] = 30
Key > a[7]

Iteration-3: low = 8 ; high = 9 ; mid = 8


a[8] = 66
Key > a[8]

Iteration-4: low = 9 ; high = 9 ; mid = 9


a[9] = 99
Key > a[9]
Key element is at 9 position

You might also like