BinarySearch source Program
public class BinarySearch {
public static int BinarySearch (int[] DataSet, int data) {
int beginindex = 0; //define starting position
int endIndex = dataset.length-1; Define End Position
int midindex =-1; //define Midpoint
if (Data <dataset[beginindex]| | data>dataset[endindex]| | Beginindex>endindex) {
return-1; The data found in the dichotomy must be ordered, so that if you compare the first element and the last element, you can determine whether the data you are looking for is in the array
}
while (beginindex <= endIndex) {
Midindex = (beginindex+endindex)/2;//initialize midpoint
if (data <dataset[midindex]) {
endIndex = midIndex-1; If the data you are looking for is smaller than the midpoint position, define the end of the lookup at the midpoint
} else if (Data>dataset[midindex]) {//If the data being found is less than the midpoint position, the start position of the lookup is defined in the midpoint
beginindex = midindex+1;
}else {
return midindex; Returns the location of the found data
}
}
return-1;
}
public static void Main (string[] args) {
int[] test1 = {38,48,59,61,72,99,101}; Test array
System.out.print ("You find the data location in:" + Binarysearch.binarysearch (test1,59));
}
}
Java Learning Data-java Common algorithm-two-point lookup algorithm