1. 程式人生 > >【數據結構】二分查找

【數據結構】二分查找

循環 star end sta 條件 while pub 遞歸 數據

/**
* 循環實現二分查找算法
*/
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 int binarySearchRecursive(int[] arr, int x, int startIndex, int endIndex){
int middle = (startIndex + endIndex) / 2;
//三個終止條件
if(x < arr[startIndex] || x > arr[endIndex] || startIndex > endIndex){
return -1;
}
if (x < arr[middle]){
return binarySearchRecursive(arr, x, startIndex, middle - 1);
}else if (x > arr[middle]){
return binarySearchRecursive(arr, x, middle + 1, endIndex);
}else{
return middle;
}
}

【數據結構】二分查找