Upper bound and lower bound prob

-1 not print in output
#include <bits/stdc++.h>
using namespace std;
int upper_bound(int a[],int n,int key)
{
int s=0;
int e=n-1;
int ans=-1;

  while(s<=e)
  {
      int mid=s+e/2;
  
  if(a[mid]==key)
  {
      ans=mid;
      e=mid-1;

  }
  else if (a[mid]>key)
  {
      e=mid-1;

  }
     else{
     
     s=mid+1;
     }

}
return ans;

}

int lower_bound(int a[],int n,int key)
{
int s=0;
int e=n-1;
int ans=-1;

  while(s<=e)
  {
      int mid=(s+e)/2;
  
  if(a[mid]==key)
  {
      ans=mid;
      s=mid+1;

  }
  else if(a[mid]>key)
  {
      e=mid-1;

  }
     else{
     
     s=mid+1;
     }

}
return ans;

}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int t;
cin>>t;
while(t–)
{
int key;
cin>>key;

int ans = upper_bound(a,n,key);
cout<<ans<<" ";
ans= lower_bound(a,n,key);
cout<<ans;
cout<<endl;
ans=0;
}
return 0;

}

hey @afzalkhan.lma, please share the code saved in coding blocks ide.

hey @afzalkhan.lma, there are some small mistakes in your code, I have made changes to your code.You can check them here. https://ide.codingblocks.com/s/104850

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like