How to implement binary search algorithm using java
How to use Java to implement the binary search algorithm
The binary search algorithm is an efficient search method suitable for sorted arrays. Its basic idea is to continuously narrow the search range, compare the search value with the elements in the middle of the array, and decide whether to continue searching the left half or the right half based on the comparison result until the target element is found or the search range is reduced to empty.
Let’s introduce in detail how to implement the binary search algorithm in Java.
Step 1: Implement the binary search method
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) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; //表示未找到目标元素 } }
Step 2: Test the binary search method
public class Main { public static void main(String[] args) { int[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; //已排序数组 int target = 12; //要查找的目标元素 int index = BinarySearch.binarySearch(arr, target); if (index != -1) { System.out.println("目标元素在数组中的位置为:" + index); } else { System.out.println("未找到目标元素"); } } }
The above code first defines a BinarySearch
class, in which Contains a static method binarySearch
for implementing the binary search algorithm. In the binarySearch
method, we define two pointers left
and right
to point to the leftmost and rightmost elements of the search range respectively. In a loop, the index of the middle element mid
is calculated and then the lookup value is compared with arr[mid]
. If the two are equal, it means that the target element is found and its index value mid
is returned. If the search value is greater than arr[mid]
, move the left
pointer one position to the right and narrow the search range to the right half. If the search value is less than arr[mid]
, move the right
pointer one position to the left and narrow the search range to the left half. The loop continues until the target element is found or the search range is empty. If the target element is not found after the loop ends, -1 is returned to indicate that it was not found.
In the main
method of the Main
class, we create a sorted array arr
and a target element to be found target
. Then call the binarySearch
method of the BinarySearch
class to perform a binary search, and store the returned result in the index
variable. Finally, it is judged whether the target element is found based on the returned result, and the corresponding result is printed.
Through the above code examples, we can see that implementing the binary search algorithm in Java is very simple and only requires a few lines of code to complete. This method has a search time complexity of O(logn), which is very efficient and suitable for large sorted arrays. If multiple search operations are required, the sorting operation of the array can be split separately to improve efficiency.
I hope this article will help you understand and use the binary search algorithm!
The above is the detailed content of How to implement binary search algorithm using java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
