# [置顶] 二分查找目标元素索引

631人阅读 评论(0)

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));
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：495014次
• 积分：3638
• 等级：
• 排名：第8967名
• 原创：63篇
• 转载：48篇
• 译文：0篇
• 评论：39条
阅读排行
评论排行
最新评论