search
HomeComputer TutorialsComputer KnowledgeHow to implement Java binary search using recursive algorithm

How to implement the recursive algorithm of binary search in java

public class Binary recursive search {

public static void main(String[] args) is the entry point of the Java program and the starting position of program execution. In this method, the main logic and functionality of the program can be written. This method must be defined in a specific format before it can be called and executed by the Java virtual machine. In the parameter list of the main method, args is a string array that can be used to receive command line parameters. By writing code in the main method, we can implement various functions, such as printout, calculation, loop, conditional judgment, etc. {

//Define the array. Note that the binary search array must be an ordered array!

int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15, 17 }; is the declaration and initialization statement of an integer array, which contains 9 elements. The value of each element is 1, 3, 5, 7, 9, 11, 13, 15, 17. In this way, we create an integer array named arr and assign it an initial value. In subsequent programs, we can use this array to perform various operations, such as searching, sorting, and counting

//Accept the return value after the search: index value, if not, it is -1;

//Test search element: 9

int a = binarySearch(arr, 9, 0, arr.length - 1);

System.out.println("The index position of the number being searched is: " a);

}

//The parameter list is: the array to be searched, the number to search for, the head index, and the tail index!

public static int binary(int[] arr, int key, int start, int end) // Recursion

{

//Create every time you come in, the intermediate index value!

int mid = (star end) / 2;

If the number to be searched is less than the starting index or greater than the ending index, or the starting index is greater than the ending index, it means that the number does not exist and -1 is returned.

if (key arr[end] || start > end) {

return -1;

}

//If the middle value is less than the number being searched, redefine the header index and move it to the middle 1 position, so that half of the numbers can be filtered out!

if (arr[mid]

//Start recursion!

return binary(arr, key, mid 1, end); // Continue binary search in the second half of the array

//Otherwise, if the middle value is greater than the number being searched, move the tail index back to the middle position of -1, so that half of the numbers can be filtered out!

} else if (arr[mid] > key) {

//Start recursion!

return binary(arr, key, start, mid - 1);

} else {

//If not, it is found and returns to the index!

return mid;

}

}

}

How to implement Java binary search using recursive algorithm

Master programming JAVA language uses recursive algorithm and 1 2 3 4 100 or 11 13 15

first question:

public class CalSum {

public static void main(String[] args) is the entry point of the Java program and the starting position of program execution. In this method, the main logic and functionality of the program can be written. This method must be defined in a specific format before it can be called and executed by the Java virtual machine. In the parameter list of the main method, args is a string array that can be used to receive command line parameters. By writing code in the main method, we can implement a variety of functions, such as printout, calculation, looping, conditional judgment, etc.

{

CalSum calSum = new CalSum();

int result = calSum.calculate(100); // Call the calculate method of the calSum object, pass in the parameter 100, and assign the result to the result variable.

System.out.println("The sum of 1 2 3 ... 100 is equal to" result);

}

public int calculate(int number)

{

int result = 0;

if(number == 1)

{

result = 1;

}

else

{

result = number calculate(number - 1); The result is to add the current number and the return value of number-1. This expression can be calculated recursively. Each time the recursive call is made, the value of number will be decremented by 1 until the recursion stops when number equals 1. The return value of the recursive call will be continuously accumulated into the final result. In this way, we can get the sum of a sequence.

}

return result;

}

}

What are the algorithms of recursion and iteration in java

Iteration is an ordinary loop.

Example: Add from 1 to 10

int sum=0

for(int i=0;i

sum=sum i;

}

Recursion means that a function calls itself directly or indirectly.

For example: Once upon a time there was a big monk and a little monk in a temple. The big monk asked the little monk to tell a story. The little monk said that once upon a time there was a big monk and a little monk in a temple. The little monk asked the big monk to tell a story. In the story, the big monk went on to say that once upon a time there was a big monk and a little monk in a temple. They practiced and studied Buddhism together every day.

Characteristics of recursion:

There must be three conditions:

1. Call yourself indirectly or directly.

2. When playing the game, be sure to set conditions for exiting. For example, the great monk will stop listening to the story if his mouth is dry. If exit conditions are not set, the game may fall into an infinite loop.

3. There must be a logical body (what you want to do);

public int sum(int x){

if(x

return x;

}

return x sum(x-1);

}

int s=10;

int total=sum(s);

In this example, the sum function always calls itself, return x sum(x-1);

sum has exit conditions, x

The final result is to return 10 9 8 7 ... 1

In many cases, both iteration and recursion can achieve the same function, but there are some functions that iteration cannot complete. In addition, recursive code is more concise, and proficient use of recursion can improve code quality.

The above is the detailed content of How to implement Java binary search using recursive algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Excel办公网. If there is any infringement, please contact admin@php.cn delete
Fixed: Windows Update May Have Automatically Replaced AMD - MiniToolFixed: Windows Update May Have Automatically Replaced AMD - MiniToolApr 18, 2025 am 12:51 AM

If your PC runs on an AMD chipset, you may receive the “Windows Update may have automatically replaced AMD” error message when using it. Don’t worry! This post from php.cn provides some solutions for you.

Microsoft Sway vs PowerPoint - Which One to Choose?Microsoft Sway vs PowerPoint - Which One to Choose?Apr 18, 2025 am 12:50 AM

What is Microsoft Sway and what is PowerPoint? These two are different presentation tools to facilitate people’s working and studying. So, what’s the difference between them and how choose between them. This post on php.cn Website will give you some

[Must-Know] Win 10 Offline Installer: Install Win 10 22H2 Offline[Must-Know] Win 10 Offline Installer: Install Win 10 22H2 OfflineApr 18, 2025 am 12:49 AM

Is there any Windows 10 offline installer for you to install the latest Windows 10 offline or without the internet? Of course, yes. php.cn Software shows you how to get a Windows 10 offline installer in this post.

Guide - How to Stop Expired Windows Server Auto-Shutdown?Guide - How to Stop Expired Windows Server Auto-Shutdown?Apr 18, 2025 am 12:48 AM

Some users report that they meet the Windows Server auto-shutdown issue after the license expires. This post from php.cn teaches you how to stop expired Windows Server auto-shutdown. Now, keep on your reading.

The File Can't Be Displayed in OneDrive - How to Resolve It?The File Can't Be Displayed in OneDrive - How to Resolve It?Apr 18, 2025 am 12:47 AM

Are you struggling with the “the file can’t be displayed” error when accessing the specific folder? Some users are complaining about this trouble and looking for useful measures. This article about the file can’t be displayed OneDrive from php.cn wil

Street Fighter 6 System Requirements – Are You Ready for It? - MiniToolStreet Fighter 6 System Requirements – Are You Ready for It? - MiniToolApr 18, 2025 am 12:46 AM

Street Fighter 6 is a fighting game published by Capcom and belongs to the Street Fighter franchise that has attracted a bunch of game fans. Some people hope to play this game on PCs. To do that, you need to meet some Street Fighter 6 system requirem

How to Show Drive Letter Before Drive Name Windows 10/11 - MiniToolHow to Show Drive Letter Before Drive Name Windows 10/11 - MiniToolApr 18, 2025 am 12:45 AM

Drive names (volume labels) are displayed before the drive letters by default in Windows. Do you know how to show drive letters before drive names? This post from php.cn tells you how to show drive letters first in File Explorer.

Exact Steps to Turn Off/On the Language Bar in Windows 10/11Exact Steps to Turn Off/On the Language Bar in Windows 10/11Apr 18, 2025 am 12:44 AM

The language bar is useful for a multilanguage Windows user. You can change the language by simply clicking. Some people want to turn off/on the language bar on the taskbar. Do you know how to do it? If you don’t know, read this php.cn post to find p

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment