package com.aozhi.test;
public class BinarySearch {
/*
* 迴圈實現二分查詢演算法arr[] 已排好序的陣列x
* return 返回索引下標
*/
public static int binarySearch(int[] arr, int x) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {//判斷非空
int middle = (low + high) / 2;//折半從中間開始
if (x == arr[middle]) {//是中間的直接返回
return middle;
} else if (x < arr[middle]) {//因為他是有序的陣列,可以根據中間值作比較
high = middle - 1;
} else {
low = middle + 1;
}
return -1;
public static void main(String[] args) {
int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };
System.out.println("迴圈查詢:" + (binarySearch(arr, 6)));
package com.aozhi.test;
public class BinarySearch {
/*
* 迴圈實現二分查詢演算法arr[] 已排好序的陣列x
* return 返回索引下標
*/
public static int binarySearch(int[] arr, int x) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {//判斷非空
int middle = (low + high) / 2;//折半從中間開始
if (x == arr[middle]) {//是中間的直接返回
return middle;
} else if (x < arr[middle]) {//因為他是有序的陣列,可以根據中間值作比較
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };
System.out.println("迴圈查詢:" + (binarySearch(arr, 6)));
}
}