Linked List and Binary Search (Recursive) : Lect #11
Linked List and Binary Search (Recursive) : Lect #11
Search(Recursive)
Lect #11
Insert the node at any specified
location in linked list
Void insertsp(int n, int pos)
{
curr=head;
for(int i=1; i<pos+1; i++) {
curr=curr->next;
if(curr==NULL)
cout<<“invalid position”; }
//create and insert node
node * temp= new node;
temp->data=n;
temp->next=curr->next;
curr->next=temp;
}
delete the node at any specified
location in linked list
Void delesp(int n)
{
//go to specified node
curr=temp=head;
while(curr->next!=NULL) {
if(curr->data==n) {
cout<<“number found & deleted”;
temp->next=curr->next;
delete curr;
break;
}
temp=curr;
curr=curr->next;
}
Recursive code of Binary Search
Int binary(int [] ,int, int int);//function prototype
int binary(int a[], int key, int low, int high)
{ int mid;
if(low> high) {
return -1; }
else
mid=(low+high)/2;
return(key==a[mid]?mid:key<a[mid]?binary(a,key
,low,mid-1):binary(a,key,mid+1,high));
}
Recursive code of Binary Search(con’t)
Int main()
{
Int key, a[5], low=0, high=4;
Cout<<“enter the key value=”
cin>>key;
cout<<“enter the array=”;
for(int i=0; i<=4; i++)
cin>>a[i];
int result=binary(a,key, low, high);
cout<<“result=”<<result;
}
Assignment Question
Consider the following list:
2,10,17,45,49,55,68,85,92,98,110
using the binary search. Search the item 85 in
following list. How many comparisons are
required to find whether the following items are
in the list? Show the value low, high and mid and
the number of comparisons after each iteration
of the function.
a. 15
b. 49
c. 98
d. 99