用Java写个算法
这里是一个示例算法,用Java实现了二分查找:
public class BinarySearch { public static int binarySearch(int[] numbers, int target) { int low = 0; int high = numbers.length - 1; while (low <= high) { int mid = (low + high) / 2; if (numbers[mid] == target) { return mid; } else if (numbers[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; }
public static void main(String[] args) {
int[] numbers = { 1, 3, 5, 7, 9 };
int target = 7;
int result = binarySearch(numbers, target);
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index " + result);
}
}
}
该算法使用二分查找技术,查找一个有序数组中的元素。它的时间复杂度为O(logn)
原文地址: http://www.cveoy.top/t/topic/fgXa 著作权归作者所有。请勿转载和采集!