import java.util.Arrays;
public class MyArrayUtil {
//手动实现二分法搜素
/**
* 实现思路:
* 前提:有序
* 第一步:将数组一分为二,得到中间元素的索引
* 第二步:将搜索目标与得到中间元素进行大小比较
* 如果大于,舍弃左边数据,将重点放到右边
* 第三步:重复执行一二步骤;知道左元素索引=右元素索引,结束搜所
*/
public static int myBinarySearch(int[] ary, int E) {
int leftIndex;
int rightIndex = ary.length - 1;
int midIndex = rightIndex / 2;
int tempIndex = -1;
while (true) {
if (E == ary[midIndex]) {
tempIndex = midIndex;
break;
} else if (E < ary[midIndex]) {
rightIndex = midIndex;
midIndex = rightIndex / 2;
} else if (E > ary[midIndex]) {
int temp = (rightIndex - midIndex) / 2;
if (temp == 0 && E == ary[rightIndex]) {
tempIndex = rightIndex;
break;
} else if (temp == 0 && E > ary[rightIndex]) {
break;
} else {
leftIndex = midIndex;
midIndex = leftIndex + temp;
}
}
}
return tempIndex;
}
public static int myBinarySearch02(int[] ary, int key) {
int leftIndex = 0;
int rightIndex = ary.length - 1;
while (leftIndex <= rightIndex) {
//计算得出中间元素的索引(列如:(0+8)/2=4)
int midIndex = (leftIndex + rightIndex) >>> 1;
int midVal = ary[midIndex];
if (midVal < key) leftIndex = midIndex + 1;
else if (midVal > key) rightIndex = midIndex - 1;
else return midIndex; // key found
}
return -(leftIndex + 1); // key not found.
}
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
int[] a = {10, 9, 8, 7, 6, 5, 4,4343,5435355,4345355,455,465,66,7567,768,768,788,78,78,7,87,87,8,78,7,87,};
Arrays.sort(a);
int i = MyArrayUtil.myBinarySearch(a, 5435355);
System.out.println(a[i]);
long endTime=System.currentTimeMillis()-startTime;
System.out.println(endTime);
System.out.println("+++++++++++++++++++++++");
long startTime2=System.currentTimeMillis();
int[] a2 = {10, 9, 8, 7, 6, 5, 4,4343,5435355,4345355,455,465,66,7567,768,768,788,78,78,7,87,87,8,78,7,87,};
Arrays.sort(a2);
int i2 = MyArrayUtil.myBinarySearch02(a, 5435355);
System.out.println(a2[i2]);
long endTime2=System.currentTimeMillis()-startTime2;
System.out.println(endTime2);
}
}
手动实现二分法搜素
最新推荐文章于 2024-08-30 18:40:43 发布