Why is it not showing the result?

package arrays;

public class lowerAndUpperBound {

public static int ub(int[] arr, int n) {
	int low=0;
	int high=arr.length-1;
	int ans=-1;
	while(low<=high) {
		int mid=(low+high)/2;
		if(arr[mid]==n) {
			ans=mid;
			low=mid-1;
		}
		else if(arr[mid]>n) {
			high=mid-1;
		}
		else {
			low=mid+1;
		}
	}
	return ans;
}
public static int lb(int[] arr, int n) {
	int low=0;
	int high=arr.length-1;
	int ans=-1;
	while(low<=high) {
		int mid=(low+high)/2;
		if(arr[mid]==n) {
			ans=mid;
			high=mid-1;
		}
		else if(arr[mid]>n) {
			high=mid-1;
		}
		else {
			low=mid+1;
		}
	}
	return ans;
}
public static void main(String[] args) {
	int[] arr= {3,5,6,7,6,3};
	System.out.println(lb(arr,3));
	System.out.println(ub(arr,3));
	System.out.println(lb(arr,6));
	System.out.println(ub(arr,6));
	
}

}

@laibaahsan27_1dfa992390072fd9 You have made a Silly mistake. In the upper bound function(ub) when you found the element you have to update low = mid + 1 but you have used low = mid-1 thats why youre getting Infinite iterations.
Corrected Code :


crx-lower-and-upper-bound-of-element-code


laibaahsan27_1dfa992390072fd9
Laiba Ahsan
21h
package arrays;

public class lowerAndUpperBound {

public static int ub(int[] arr, int n) {
	int low=0;
	int high=arr.length-1;
	int ans=-1;
	while(low<=high) {
		int mid=(low+high)/2;
		if(arr[mid]==n) {
			ans=mid;
			low=mid-1;
		}
		else if(arr[mid]>n) {
			high=mid-1;
		}
		else {
			low=mid+1;
		}
	}
	return ans;
}
public static int lb(int[] arr, int n) {
	int low=0;
	int high=arr.length-1;
	int ans=-1;
	while(low<=high) {
		int mid=(low+high)/2;
		if(arr[mid]==n) {
			ans=mid;
			high=mid-1;
		}
		else if(arr[mid]>n) {
			high=mid-1;
		}
		else {
			low=mid+1;
		}
	}
	return ans;
}
public static void main(String[] args) {
	int[] arr= {3,5,6,7,6,3};
	System.out.println(lb(arr,3));
	System.out.println(ub(arr,3));
	System.out.println(lb(arr,6));
	System.out.println(ub(arr,6));
	
}
}

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.