小试 二分法

需求:在小->大的有序数组中找到对应日期的位置。


public class FinderPosition {

private static int findPositionInArray(int[] i, int target) {
int cusor = 0, rangeStart = 0, rangeEnd = i.length, findCount = 0;
while (true) {
findCount++;
if(target < i[rangeStart] || target > i[rangeEnd - 1]) {
cusor = -1;
break;
}
if (target == i[cusor])
break;
cusor = (rangeEnd + rangeStart) / 2;
if (i[cusor] > target) {
rangeEnd = cusor;
}else if (i[cusor] < target){
rangeStart = cusor;
}else if (i[cusor] == target) {
break;
}
}
System.out.println("Found " + findCount +" times, the result is:" + cusor);
return cusor;
}

public static void main(String[] args) {
int[] i = { 20080130,20080131, 20080229, 20080331, 20080430, 20080530, 20080630,
20080731, 20080829, 20080901, 20080929, 20080930, 20081031,
20081128, 20081231, 20090101, 20090130, 20090227, 20090331,
20090401, 20090430, 20090501, 20090529, 20090630, 20090701,
20090731, 20090831, 20090901, 20090930, 20101014, 20101015,
20101020, 20101029, 20101031, 20101101, 20101111, 20101112,
20101114, 20101117, 20101119, 20101126, 20101129, 20101130,
20101201, 20101202, 20101203, 20101206, 20101207, 20101208,
20101209, 20101210, 20101213, 20101214, 20101215, 20101216,
20101217, 20101218, 20101220, 20101221, 20101222, 20101223,
20101224, 20101225, 20101227, 20101228, 20101230, 20101231,
20110101, 20110103, 20110104, 20110105, 20110106, 20110107,
20110110, 20110111, 20110112, 20110113, 20110114, 20110118,
20110119, 20110120, 20110121, 20110124, 20110125, 20110126,
20110126, 20110127, 20110201, 20110203, 20110207, 20110208,
20110210, 20110211, 20110214, 20110215, 20110216, 20110218,
20110221, 20110222, 20110223, 20110224, 20110225, 20110228,
20110301, 20110302, 20110303, 20110307, 20110308, 20110309,
20110310, 20110311, 20110315, 20110316, 20110317, 20110318,
20110323, 20110324, 20110325, 20110328, 20110329, 20110330,
20110404, 20110406, 20110407, 20110419, 20110420};

int target = 20110420;
System.out.println("Begin to find: " + target);
int position = findPositionInArray(i,target);
if (position != -1)
System.out.println("position " + position + " is: " + i[position]);

}
}


结果:
Begin to find: 20110420
Found 7 times, the result is:125
position 125 is: 20110420

2的x方 <= i.length, 循环查找次数不会多于x次.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值