共計 803 個字符,預計需要花費 3 分鐘才能閱讀完成。
折半查找法(二分查找法)是一種查找有序數組中特定元素的算法。以下是 Java 實現折半查找法的示例代碼:
public class BinarySearch {public static int binarySearch(int[] arr, int target) {int left = 0;
int right = arr.length - 1;
while (left <= right) {int mid = left + (right - left) / 2;
if (arr[mid] == target) {return mid;
}
if (arr[mid] < target) {left = mid + 1;
} else {right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {int[] arr = {1, 3, 5, 7, 9, 11};
int target = 7;
int index = binarySearch(arr, target);
if (index != -1) {System.out.println(" 元素 " + target + " 在數組中的索引位置為 " + index);
} else {System.out.println(" 元素 " + target + " 不在數組中 ");
}
}
}
在上述代碼中,binarySearch 方法接受一個有序數組 arr 和目標元素 target 作為參數,返回目標元素在數組中的索引位置,如果目標元素不在數組中,則返回 -1。
該方法通過設定左邊界 left 和右邊界 right 來定義查找的范圍,然后在循環中計算中間位置 mid,并通過與目標元素的比較來縮小查找范圍。如果中間元素等于目標元素,就返回中間位置;如果中間元素小于目標元素,說明目標元素在右半部分,將左邊界移動到 mid+1;如果中間元素大于目標元素,說明目標元素在左半部分,將右邊界移動到 mid-1。最終,如果找到目標元素,則返回其索引位置,否則返回 -1。
丸趣 TV 網 – 提供最優質的資源集合!
正文完