0% found this document useful (0 votes)
18 views3 pages

Daa 2

PROGRAM EXP

Uploaded by

Pratistha Sanwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Daa 2

PROGRAM EXP

Uploaded by

Pratistha Sanwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Program No.

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()
{

Name: Pratistha Sanwal Roll no. Page | 1


2200321540123
int f=0;
int arr[]={9,78,5,78,4};
int key=78;
f=binary(arr,0,4,key);
if(f ==-1)
cout<<"element not found";
else
cout<<"element found at index "<<f;
return 0;
}

OUTPUT:

(II) For the recursive linear search:


Step 1: Start with an array and target: Begin at index 0 and compare the current element with
the target.
Step 2: Base Case: If the index exceeds the length of the array, return -1 (target not found).
Step 3: Check current element: If the current element matches the target, return the current
index.
Step 4: Recursive Step: If not, recursively call the function with the next index (index + 1).
Step 5: Return result: Continue until the target is found or return -1 if not found.
CODE:
#include <iostream>
int linear(int arr[],int size,int key)
{ if(size<0)
return -1;
if(arr[size]!=key)
return linear(arr,size-1,key);
else

Name: Pratistha Sanwal Roll no. Page | 2


2200321540123
return 1;
return -1;
}
using namespace std;
int main()
{
int f=0;
int arr[]={9,89,5,78,4};
int key=89;
f=linear(arr,4,key);
if(f==1)
cout<<"element found at index "<<f;
else
cout<<"element not found";
return 0;
}

OUTPUT:

Name: Pratistha Sanwal Roll no. Page | 3


2200321540123

You might also like