# 二分查找目标元素索引

package com.zhangry.search;

public class BinarySearch {

public static void main(String[] args) {
int[] arrayForSearch = {1,2,3,4,5,6,7,8,9,10};
int start = 0;
int end = arrayForSearch.length-1;
int target = 3;
System.out.println(target+"在此数组中的索引为: "+binarySearch(arrayForSearch,start,end,target));
}

private static int binarySearch(int[] arrayForSearch,int start,int end,int target){
int current = (start+end)/2;
if(arrayForSearch[current] == target){
return current;
}else if(arrayForSearch[current] > target){
end =  current;
return binarySearch(arrayForSearch,start,end,target);
}else if(arrayForSearch[current] < target){
start = current;
return binarySearch(arrayForSearch,start,end,target);
}
return -1;
}

}


package com.zhangry.search;

public class WhileBinarySearch {
/**
* 二分查找算法
* @param srcArray　有序数组
* @param des　查找元素 *
* @return des的数组下标，没找到返回-1
*/
public static int binarySearch(int[] srcArray, int des) {
int low = 0;
int high = srcArray.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (des == srcArray[middle]) {
return middle;
} else if (des < srcArray[middle]) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}

public static void main(String[] args) {
int[] src = new int[] { 1, 3, 5, 7, 8, 9 };
System.out.println(binarySearch(src, 8));
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：二分查找目标元素索引 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)