Daa 2
Daa 2
01
AIM: Program for Recursive Binary & Linear Search.
ALGO:
(I) For the recursive binary search:
Step 1: Divide the search space into two halves by finding the middle index “mid”.
Step 2: Compare the middle element of the search space with the key.
Step 3: If the key is found at middle element, the process is terminated.
Step 4: If the key is not found at middle element, choose which half will be used as the next
search space.
(i) If the key is smaller than the middle element, then the left side is used for
next search.
(ii) If the key is larger than the middle element, then the right side is used
for next search.
Step 5: This process is continued until the key is found or the total search space is exhausted.
CODE:
#include <iostream>
using namespace std;
int binary(int arr[],int low,int high,int key)
{
while(low<=high){
int mid=(low)+(high-low)/2;
if(arr[mid]==key)
return mid;
else if(arr[mid]>key)
return binary( arr, low, mid-1, key);
else if(arr[mid]<key)
return binary(arr, mid+1, high, key);
}
return -1;
}
int main()
{
OUTPUT:
OUTPUT: