java小程序 实例 二分法查找

时间:2021-11-04 18:02:52

使用二分法在一个数组中查找一个数:

package com.test;

public class BinaryFind {





private final static int size = 500000;





public static void main(String[] args) {

int[] a = new int[size];

for (int i = 0; i < size; i++) {

a[i] = i + 1;

}

find(a, -500001155);

}





private static void find(int a[], int n) {

int middle = 0;

int start = 0;

int end = a.length;

try {

while (start < end) {

middle = (start + end) / 2;

if (n == a[middle]) {

System.out.println("找到了" + n);

return;

} else if (n > a[middle]) {

start = middle + 1;

} else {

end = middle - 1;

}

}

} catch (Exception e) {

e.printStackTrace();

System.out.println(start + "|" + end + "|" + middle);

// TODO: handle exception

}



System.out.println("找不到" + n);





}

}

注:数组有序,从大到小,