二分查找比較簡單,直接上代碼.
ps:二分查找 只針對有序的數據
/**
* 二分查找 只針對有序的數據
*
* @author
* @date 2018年3月6日
*/
public class BinarySearchTest {
public static void main(String[] args) {
// 必須是有序數組
int[] arr = { 2, 4, 5, 8, 9, 10, 11, 13, 25, 28 };
int s = 0, // 開始位置
e = arr.length - 1, //結束位置
m = 0; // 中間位置
int num = 4; //要查找的數字.
while (s<=e) {
m = (s+e)/2;
if(num == arr[m]) {
System.out.println("這個數存在,這個數是: " + arr[m]);
return;
} else if(num < arr[m]) {
e = m-1;
} else {
s = m+1;
}
}
System.out.println("你找的數不存在..");
}
}
--end.