public class binarysearch {
public static int search(num, target_value) {
int low = 0;
int mid;
int high = num.length - 1;
while (low < high) {
mid = (low high) / 2;
if (num[mid] == target_value) {
return mid;
}
if (num[mid] < target_value){
low = mid 1;
} else {
high = mid - 1;
}
}
}
public static void main(String[] args) {
binarysearch ob = new binarysearch();
int target_value = 69;
int[] num = {10,23,45,11,69,81};
int result = ob.search(num,target_value);
if (result == -1) {
System.out.println("Element not present");
} else {
System.out.println("Element is present" mid);
}
}
}
Could someone help me what exactly I am doing wrong here. I am facing a compilation error while executing my code.
I was trying to implement Binary Search and I am receiving this error :
/binarysearch.java:2: error: <identifier> expected
public static int search(num,target_value)
^
/binarysearch.java:2: error: <identifier> expected
public static int search(num,target_value)
^
2 errors
CodePudding user response:
You have to add type parameters in the method
public static int search(int[] num, int target_value)
and if you make the method static you dont have to declaration the object
you can call the method directly
int result = search(num,target_value);
CodePudding user response:
As @Bahij.Mik mentioned in the comments, you are missing the types in the method signature. So change the search
method to:
public static int search(int[] num, int target_value) {
..
}
N.B. Check also this Guide to the Static Keyword in Java!