Example
package com.w3schools;
public class Test {
public static int binarySearch(int[] data,int start, int end,int key){
if (start < end) {
int mid = start + (end - start) / 2;
if (key < data[mid]) {
return binarySearch(data, start, mid, key);
} else if (key > data[mid]) {
return binarySearch(data, mid+1, end , key);
} else {
return mid;
}
}
return -(start + 1);
}
public static void main(String args[]){
int[] data= {50,127,130,150,170,910,1009};
int key = 130;
System.out.println(key+" is found at index: "+binarySearch(data,0, data.length, key));
}
} |
package com.w3schools;
public class Test {
public static int binarySearch(int[] data,int start, int end,int key){
if (start < end) {
int mid = start + (end - start) / 2;
if (key < data[mid]) {
return binarySearch(data, start, mid, key);
} else if (key > data[mid]) {
return binarySearch(data, mid+1, end , key);
} else {
return mid;
}
}
return -(start + 1);
}
public static void main(String args[]){
int[] data= {50,127,130,150,170,910,1009};
int key = 130;
System.out.println(key+" is found at index: "+binarySearch(data,0, data.length, key));
}
}
Output