Please help everything is correct


I am not getting any output please help

@radhagovinda008
Your BinarySearchLast is going in a infinite loop due to incorrect logic.
Hence you are not getting any output.Try to correct the BinarySearchLast function and then revert back here.

can you please give some suggestions on my logic because i dry run my code and it works

@radhagovinda008
At line 27 of your code.
int result = -1;
while (i <= len) {

		int mid = (i + len) / 2;
		if (arr[mid] == search) {
			
			result = mid;
			len = mid + 1;
		} else if (arr[mid] > search)
			len = mid - 1;
		else
			i = mid + 1;

	}

	return result;

The above code snippet calculates mid,and if search founds at mid,it makes len=mid+1.
Now consider an example Array:
1 2 3 3 4
We have to find last element of 3 in this array.
Lets dry run your code line by line.
1st iteration of while: initially i=0,len=4;
mid =2;hence arr[mid]>search, so len=mid-1=> len=1.

2nd iteration of while: i=0,len=1,hence mid=0.
resulting in arr[mid]<search, hence i=mid+1=> i=1;

3rd iteration : i=1,len=1,mid=1.
Now,arr[mid]==search.
result=mid;=>result=1.
len=mid+1.

4th iteraton and so on:i=1,len=1,mid=1.
Now,arr[mid]==search.
result=mid;=>result=1.
len=mid+1.
.
.
.
.
While loop never terminates as i=1,len=1; i never exceeds len.

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.