用java写一个二分排序算法
以下是一个使用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; // 如果找不到目标元素,则返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 5;
int index = binarySearch(arr, target);
if (index != -1) {
System.out.println("目标元素 " + target + " 在数组中的索引位置为 " + index);
} else {
System.out.println("目标元素 " + target + " 不在数组中");
}
}
}
在上述代码中,binarySearch 方法接收一个有序的整数数组 arr 和一个要查找的目标元素 target。它使用二分查找算法在数组中查找目标元素,并返回目标元素的索引位置。如果找不到目标元素,则返回 -1。
在 main 方法中,我们使用一个示例数组 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 来演示如何使用 binarySearch 方法查找目标元素 5。如果找到目标元素,则打印出目标元素的索引位置;否则,打印出目标元素不在数组中的信息。
希望以上代码能够满足您的需求
原文地址: https://www.cveoy.top/t/topic/hEE6 著作权归作者所有。请勿转载和采集!