@@ -23,28 +23,27 @@ public int find(T[] arr, T target) {
2323
2424 // Recursive binary search function
2525 public int binsear (T [] arr , int left , int right , T target ) {
26- if (right >= left ) {
27- int mid = left + ( right - left ) / 2 ;
28-
29- // Compare the element at the middle with the target
30- int comparison = arr [ mid ]. compareTo ( target ) ;
26+ if (right < left ) {
27+ // Element is not present in the array
28+ return - 1 ;
29+ }
30+ final int mid = left + ( right - left ) / 2 ;
3131
32- // If the element is equal to the target, return its index
33- if (comparison == 0 ) {
34- return mid ;
35- }
32+ // Compare the element at the middle with the target
33+ final int comparison = arr [mid ].compareTo (target );
3634
37- // If the element is greater than the target, search in the left subarray
38- if (comparison > 0 ) {
39- return binsear ( arr , left , mid - 1 , target ) ;
40- }
35+ // If the element is equal to the target, return its index
36+ if (comparison == 0 ) {
37+ return mid ;
38+ }
4139
42- // Otherwise, search in the right subarray
43- return binsear (arr , mid + 1 , right , target );
40+ // If the element is greater than the target, search in the left subarray
41+ if (comparison > 0 ) {
42+ return binsear (arr , left , mid - 1 , target );
4443 }
4544
46- // Element is not present in the array
47- return - 1 ;
45+ // Otherwise, search in the right subarray
46+ return binsear ( arr , mid + 1 , right , target ) ;
4847 }
4948
5049 public static void main (String [] args ) {
0 commit comments