Java写一个二分查找
时间: 2023-05-17 17:03:04 浏览: 50
二分查找是一种常见的查找算法,可以在有序数组中快速查找指定元素。以下是 Java 实现二分查找的代码:
```java
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;
}
```
这个方法接收一个有序数组和一个目标值作为参数,返回目标值在数组中的索引,如果目标值不存在则返回 -1。
相关问题
java写一个二分查找
好的,下面是一个简单的 Java 二分查找示例:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int x) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 没有找到指定元素,返回 -1
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 12, 14, 16};
int x = 10;
int index = binarySearch(arr, x);
if (index == -1) {
System.out.println("元素 " + x + " 不存在于数组中");
} else {
System.out.println("元素 " + x + " 在数组中的索引为 " + index);
}
}
}
```
该示例使用 `binarySearch` 方法实现二分查找,接收一个整型数组和要查找的元素作为参数,返回该元素在数组中的索引,如果该元素不存在于数组中,返回 -1。
在 `main` 方法中,我们定义了一个整型数组 `arr` 和要查找的元素 `x`,然后调用 `binarySearch` 方法查找该元素在数组中的索引,并输出结果。
用java写一个二分查找树
好的,以下是用 Java 写一个二分查找树的基本代码:
```java
class Node {
int key;
Node left, right;
public Node(int data) {
key = data;
left = right = null;
}
}
class BinarySearchTree {
Node root;
public BinarySearchTree() {
root = null;
}
void insert(int key) {
root = insertNode(root, key);
}
Node insertNode(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertNode(root.left, key);
} else if (key > root.key) {
root.right = insertNode(root.right, key);
}
return root;
}
void inorder() {
inorderTraversal(root);
}
void inorderTraversal(Node root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.key + " ");
inorderTraversal(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
System.out.println("Inorder traversal of the binary search tree: ");
bst.inorder();
}
}
```
这里我们定义了一个节点(Node)类和一个二分查找树(BinarySearchTree)类。节点类存储了键值以及左右子节点;而二分查找树类则包含了对节点的插入(insert)和中序遍历(inorder)方法。
我们在 main() 方法中创建了一颗二分查找树,插入了一些数据,并且打印了中序遍历结果。
希望这份代码可以帮到您。