Binary Search implementation via java


Binary Search implementation via java



Please see the below java source code for binary search implementation


public class Main {
public static void main (String args) {

int x= {1,2,3,4,5,6,7,8,9,10,11};
int y=binarySearch(x,11);
System.out.println(y);


}public static int binarySearch(int arr,int value) {
int searchedIndex = -1;
int first=0;
**int last=arr.length-1;**
int mid;

while(first<=last) {
mid=(first+last)/2;

if(arr[mid]==value) {
searchedIndex=mid;
break;
}else {
if(value<arr[mid]) {
last=mid-1;
}else {
first=mid+1;
}
}
}




return searchedIndex;
}


}



int last=arr.length-1 is -1 compulsory or not.I feel that code works fine either last=arr.length-1. If its compulsory please explain why.





The array starts with 0 and ends with lengh-1. What is the problem?
– JF Meier
2 mins ago





Your question is a little unclear, but searching arrays you have to get the length -1 because the array indexes start at 0. So if there are 5 elements in an array, you get them by array[0], array[1] etc up to array[4].
– notyou
23 secs ago


array[0]


array[1]


array[4]




2 Answers
2



Arrays already have a method binarySearch you can just use :


binarySearch


int x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int r = Arrays.binarySearch(x, 11);



Yes it’s true but is it compulsory to include -1 . When we include-1 ,mid calculation value change automatically






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter