1, two-part search method to explain: if the use of binary search method to do the operation, the array must be ordered. So when you start out with an unordered array, you sort the ordered array first.
public class test2{
public static void Main (string[] args) {
--Find the location of a data
int number = 8;
--Define the number of groups
int[] arr = new int[]{7,2,10,9,45,3,4};
Sorting and dichotomy are used simultaneously.
int[] arr = new int[]{2,3,4,7,9,10,45};
--Start subscript
int start = 0;
--Termination of subscript
int end = Arr.length-1;
--the intermediate subscript to be obtained
int middle;
--Stores the container where the array is located (if the last printed index is 1, the data that is found does not exist)
int index =-1;
while (Start<=end) {
Middle = (start+end)/2;
if (Number==arr[middle]) {
index = middle+1;
Break
}else if (Number<arr[middle]) {
end = Middle-1;
}else if (Number>arr[middle]) {
start = Middle +1;
}
}
if (index==-1) {
System.out.println ("Didn't find the data needed!!! ");
}else{
System.out.println ("The location of the data is:" +index);
}
} }
2, import Java.util.Scanner;
public class binarysearch{
public static void Main (String [] args) {
int [] array={10,20,30,40,50,60,70,80};
System.out.println ("Please enter the number to find:");
Scanner input=new Scanner (system.in);
int Number=input.nextint ();
int index=-1;
int start=0;
int end=array.length-1;
int middle;
while (Start<=end) {
Middle= (Start+end)/2;
if (Number==array[middle]) {
index=middle+1;
Break
}
if (Number>array[middle]) {
start=middle+1;
}
if (Number<array[middle]) {
end=middle-1;
}
}
if (index==-1) {
System.out.println ("not Found");
}else{
System.out.println ("found" +index);
} }}
Java Array 2 (2015-8-27)