packageJava base 04_ one-dimensional array;// Binary search algorithm
// True, binary search, sort first
/* Binary algorithm step description ① First determine the middle position of the entire search interval mid = (left + right) / 2 ② compare the keyword value with the keyword value of the middle position; If it is equal, the search succeeds. If it is greater than, the search continues in the back (right) half region. If it is less than, the search continues in the front (left) half region. Finally, you get the result: either the search succeeds or the search fails. The storage structure of split - half search is one-dimensional array. Example of split search algorithm */
public class ErFenArrayDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arry = {2.3.5.12.6.24.74.67.5.11.22.54.28.28.9.19.10};
		for(int i = 0; i<arry.length-1; i++) {for(int j=0; j<arry.length-1; j++) {if(arry[j]>arry[j+1]) {
					int linshi = arry[j];
					arry[j]=arry[j+1];
					arry[j+1]=linshi; }}}for(int i=0; i<arry.length-1; i++) { System.out.print(arry[i]+",");	/ / from small to large, output 2,3,5,5,6,9,10,11,12,19,22,24,28,28,54,67
		}
		System.out.println();
		int findNume=22;// The number to find
		int start = 0;
		int end=arry.length-1;
		System.out.println("end"+end);/ / 16
		int findIndex=-1;
		int middle=0;
		while(start<=end) {/ / 0 < 16, 9 < 16
			System.out.println("start1:"+start);/ / 0, 9
			middle=(start+end)/2;// take the index of the middle value 8,12
			System.out.println("middle:::"+middle);
			if(findNume>arry[middle]) {/ / 22 more than 11, 22 < 24
				// If the number to be queried is greater than the median value, the starting value is converted to the index value equal to the median value plus one, and the query continues to the larger number.
				start=middle+1;//star=9,
				System.out.println("start2:"+start);
			}
			if(findNume<arry[middle]) {
				// If the number to be queried is less than the median value, the starting value is converted to the index value equal to the median value plus one, and the query continues to the smaller number.
				end=middle-1;
			//	System.out.println(end);
			}
			if(findNume==arry[middle]) {
				// If the number to be queried is equal to the median value, then the query is directly found.
				findIndex=middle;
			//	System.out.println(findIndex);
				break; }}if(findIndex==-1) {
			System.out.println("Not found.");
		}else {
			System.out.println("Found:"+arry[findIndex]); }}}Copy the code