java 数组二分法

代码如下:

package 数组常见的算法;

public class 数组的二分查找 {

public static int Intsearch(int[] Array, int serchNum) {
	int res;

// 数组复制
int[] midArray;
int p = 2;
midArray = new int[Array.length];
for (int i = 0; i < Array.length; i++) {
midArray[i] = Array[i];
}

	int lon = midArray.length;
	int lom = 0;
	while(true) {
		System.out.println(lon);
		System.out.println(lom);
		int midNum = lom + (lon-lom)/2 + 1;  //采用进1法

		if(midNum == 2 || midNum == midArray.length ) {
			 if (midArray[midNum-1] == serchNum) {
					res = midNum -1 ;
					break;
			
			 } else if(midArray[midNum-2] == serchNum){
				res = midNum - 2;
				break;
			 } else {
					System.out.println("所找元素不在改数组中");
					res = -1;
					break;
				 }
			
		
		}else if (midArray[midNum-1] == serchNum) {
			res = midNum-1;
			break;
		}else if (midArray[midNum-1] > serchNum) {

// 前
lon = midNum;
lom = lom;

		}else if (midArray[midNum-1] < serchNum) {

// 后
lon = lon;
lom = midNum;

		}
		
	}
	
return res;
}


public static void main(String[] args) {
	// TODO Auto-generated method stub
	int[] arr1 = new int[] {-33,-21,-9,21,54,678,999,1931,9412,10000,100000}; 
	
	//二分法:

// 前提:所要查找的数组必须有序

	int seNum = 100000;
	int k = Intsearch(arr1, seNum);
	System.out.println(k);
}

}

二分法注意:其数列必须为规则数列否则不可以用
可扩展:可将传进的数组进行排序后,在传入该函数内,可扩展类型
我就不改了,自己动手丰衣足食

你可能感兴趣的:(java,数组查找二分法,二分法,java)