1.迭代实现二分查找
public static int binarySearchIterative(int[] array, int target) { int low = 0; int high = array.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (array[mid] == target) { return mid; } else if (array[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; // 如果未找到目标元素,返回-1 }
2.递归实现二分查找:
public static int binarySearchRecursive(int[] array, int target, int low, int high) { if (low <= high) { int mid = low + (high - low) / 2; if (array[mid] == target) { return mid; } else if (array[mid] < target) { return binarySearchRecursive(array, target, mid + 1, high); } else { return binarySearchRecursive(array, target, low, mid - 1); } } return -1; // 如果未找到目标元素,返回-1 }
无论是递归还是迭代实现,二分查找都要求在已排序的数组中进行查找。确保在使用二分查找算法时,数组是有序的。如果目标元素存在于数组中,则返回其索引位置;如果目标元素不存在于数组中,则返回-1。