用java写一段二分查找代码
public class BinarySearch { public static int binarySearch(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; }
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
int target = 3;
int index = binarySearch(nums, target);
if (index == -1) {
System.out.println("Target not found.");
} else {
System.out.println("Target found at index " + index);
}
}
}
原文地址: http://www.cveoy.top/t/topic/bLys 著作权归作者所有。请勿转载和采集!