0

What mistake I have done

Binarysearch https://code.sololearn.com/c9nXLhUnWY1T/?ref=app

22nd Mar 2023, 9:36 AM
Rik Barman
Rik Barman - avatar
4 odpowiedzi
+ 2
First of all to apply binary search your array must be sorted. And the condition in while loop is also not correct. Have made a few changes. Use the below logic. Scanner sc=new Scanner(System.in); int arr[]={45,67,12,34,88,90,47,35}; Arrays.sort(arr); int mid=0,l=0,u=arr.length-1,f=0; System.out.println("Enter:"); int n=sc.nextInt(); while(l<=u) { mid=(u+l)/2; if(n<arr[mid]) { u=mid-1; } else if(n>arr[mid]) { l=mid+1; } else { f++; break; } } After this you can have the same code as yours.
22nd Mar 2023, 9:47 AM
Avinesh
Avinesh - avatar
0
Entering 45 it is not giving output
22nd Mar 2023, 9:45 AM
Rik Barman
Rik Barman - avatar
0
Thanks
22nd Mar 2023, 9:57 AM
Rik Barman
Rik Barman - avatar