java实现递归算法_如何在Java中实现二进制搜索算法而无需递归

java实现递归算法

by javinpaul

由javinpaul

Hello everyone! I have published a lot of algorithms and data structure articles on my blog, but this one is the first one here. In this article, we’ll examine popular fundamental algorithms for interviews.

大家好! 我在博客上发表了很多算法和数据结构文章,但这是本文的第一篇。 在本文中,我们将研究流行的基本面试算法

Yes, you guessed it right: you need to implement a binary search in Java, and you need to write both iterative and recursive binary search algorithms.

是的,您猜对了:您需要在Java中实现二进制搜索 ,并且需要编写迭代和递归二进制搜索算法。

In computer science, a binary search, or half-interval search, is a divide and conquer algorithm that locates the position of an item in a sorted array. Binary searching works by comparing an input value to the middle element of the array.

在计算机科学中,二进制搜索或半间隔搜索是一种分而治之的算法 ,用于定位项目在已排序数组中的位置 。 二进制搜索通过将输入值与数组的中间元素进行比较来工作。

The comparison determines whether the element equals the input, is less than the input, or is greater than the input.

比较将确定元素等于输入,小于输入还是大于输入。

When the element being compared equals the input, the search stops and typically returns the position of the element.

当要比较的元素等于输入时,搜索将停止,并且通常会返回该元素的位置。

If the element is not equal to the input, then a comparison is made to determine whether the input is less than or greater than the element.

如果元素不等于输入,则进行比较以确定输入是否小于或大于元素。

Depending on the result, the algorithm then starts over again, but only searching the top or a bottom subset of the array’s elements.

然后根据结果, 算法重新开始,但仅搜索数组元素的顶部或底部子集。

If the input is not located within the array, the algorithm will usually output a unique value indicating this like -1 or just throw a RuntimeException in Java like NoValueFoundException.

如果输入不在数组内 ,则算法通常会输出一个唯一的值,例如-1,或者仅在Java中抛出RuntimeException ,例如NoValueFoundException。

Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or determining its absence) in logarithmic time.

二进制搜索算法通常将每次连续迭代要检查的项目数量减半,从而在对数时间内定位给定的项目(或确定其不存在)。

Btw, if you are not familiar with fundamental search and sort algorithms, then you can also join a course like Data Structures and Algorithms: Deep Dive Using Java to learn fundamental algorithms.

顺便说一句,如果您不熟悉基本搜索和排序算法,那么您也可以参加“ 数据结构和算法:使用Java深入学习”一门课程,学习基本算法。

If Java is not your choice of language, you can find more recommendations for JavaScript and Python in this list of algorithms courses.

如果您不是Java语言的选择者,则可以在此算法课程列表中找到有关JavaScript和Python的更多建议。

Btw, if you prefer books, I suggest you read a comprehensive algorithm book like Introduction to Algorithms by Thomas H. Cormen.

顺便说一句,如果您喜欢书籍,我建议您阅读全面的算法书籍,例如Thomas H. Cormen的《 算法简介》

Here is some sample code which shows the logic of iterative binary search in Java:

这是一些示例代码,显示了Java迭代二进制搜索的逻辑:

Java二进制搜索实现 (Binary Search Implementation in Java)

Here is a sample program to implement binary search in Java. The algorithm is implemented recursively. Also, an interesting fact to know about binary search implementation in Java is that Joshua Bloch, author of the famous Effective Java book, wrote the binary search in “java.util.Arrays”.

这是在Java中实现二进制搜索的示例程序。 该算法是递归实现的。 另外,有关Java中二进制搜索实现的一个有趣事实是,著名的Effective Java著作的作者Joshua Bloch在“ java.util.Arrays”中编写了二进制搜索。

import java.util.Arrays;import java.util.Scanner;
/** * Java program to implement Binary Search. We have implemented Iterative* version of Binary Search Algorithm in Java** @author Javin Paul*/
public class IterativeBinarySearch {
public static void main(String args[]) {    int[] list = new int[]{23, 43, 31, 12};    int number = 12;    Arrays.sort(list);    System.out.printf("Binary Search %d in integer array %s %n", number, Arrays.toString(list));
binarySearch(list, 12);    System.out.printf("Binary Search %d in integer array %s %n", 43, Arrays.toString(list));
binarySearch(list, 43);    list = new int[]{123, 243, 331, 1298};    number = 331;    Arrays.sort(list);    System.out.printf("Binary Search %d in integer array %s %n", number,    Arrays.toString(list));
binarySearch(list, 331);    System.out.printf("Binary Search %d in integer array %s %n",   331, Arrays.toString(list));    binarySearch(list, 1333);
// Using Core Java API and Collection framework   // Precondition to the Arrays.binarySearch   Arrays.sort(list);
// Search an element   int index = Arrays.binarySearch(list, 3);
}
/** * Perform a binary Search in Sorted Array in Java * @param input * @param number * @return location of element in array */
public static void binarySearch(int[] input, int number) {int first = 0;int last = input.length - 1;int middle = (first + last) / 2;
while (first <= last) {  if (input[middle] < number) {  first = middle + 1;} else if (input[middle] == number) {
System.out.printf(number + " found at location %d %n", middle);break;} else {  last = middle - 1;}
middle = (first + last) / 2;
}
if (first > last) {  System.out.println(number + " is not present in the list.\n");}
}
}
OutputBinary Search 12 in integer array [12, 23, 31, 43]12 found at location 0Binary Search 43 in integer array [12, 23, 31, 43]43 found at location 3Binary Search 331 in integer array [123, 243, 331, 1298]331 found at location 2Binary Search 331 in integer array [123, 243, 331, 1298]1333 is not present in the list.

That’s all about how to implement binary search using recursion in Java. Along with Linear search, these are two of the essential search algorithms you learn in your computer science class.

这就是如何在Java中使用递归实现二进制搜索的全部内容。 与线性搜索一起,这是您在计算机科学课上学习的两种基本搜索算法。

The binary search tree data structure takes advantage of this algorithm and arranges data in a hierarchical structure so that you can search any node in O(logN) time.

二进制搜索树数据结构利用此算法,并以分层结构排列数据,以便您可以在O(logN)时间内搜索任何节点。

Though, you must remember that in order to use binary search, you need a sorted list or array, so you also need to consider the cost of sorting when you consider using binary search algorithm in the real world. Further Learning Data Structures and Algorithms: Deep Dive Using Java Algorithms and Data Structures — Part 1 and 2 Data Structures in Java 9 by Heinz Kabutz10 Algorithms books for Interviews10 Data Structure and Algorithm Courses for Interviews5 Free Courses to Learn Data Structure and Algorithms

但是,您必须记住,要使用二进制搜索,您需要一个排序列表或数组,因此在现实世界中考虑使用二进制搜索算法时,还需要考虑排序的成本。 进一步学习 数据结构和算法:使用Java 算法和数据结构的 深入研究— Java的 第1部分和第2部分 。Heinz Kabutz编写的Java 9中的数据结构。10 面试的算法书 10 面试的 数据结构和算法课程 5项学习数据结构和算法的免费课程

Other Data Structure and Algorithms tutorials you may like

您可能喜欢的其他数据结构和算法教程

  • How to implement Quicksort algorithm in place in Java? (tutorial)

    如何在Java中实现Quicksort算法? ( 教程 )

  • How to implement Binary Search Tree in Java? (solution)

    如何在Java中实现二进制搜索树? ( 解决方案 )

  • How to implement Quicksort algorithm without recursion? (tutorial)

    如何实现无递归的Quicksort算法? ( 教程 )

  • How to implement Insertion sort algorithm in Java? (tutorial)

    如何在Java中实现插入排序算法? ( 教程 )

  • How to implement Bubble sort algorithm in Java? (tutorial)

    如何在Java中实现冒泡排序算法? ( 教程 )

  • What is the difference between Comparison and Non-Comparison based sorting algorithm? (answer)

    基于比较和基于非比较的排序算法有什么区别? ( 回答 )

  • How to implement Bucket Sort in Java? (tutorial)

    如何在Java中实现Bucket Sort? ( 教程 )

  • How to implement a Binary Search Algorithm without recursion in Java? (tutorial)

    如何在Java中实现没有递归的二进制搜索算法? ( 教程 )

  • 50+ Data Structure and Algorithms Courses for Programmers (questions)

    面向程序员的50多种数据结构和算法课程( 问题 )

Thanks for reading this article. If you like this article then please share with your friends and colleagues. If you have any suggestion or feedback then please drop a comment.

感谢您阅读本文。 如果您喜欢这篇文章,请与您的朋友和同事分享。 如果您有任何建议或反馈,请发表评论。

PS —如果您认真提高自己的算法技能,我认为“ 数据结构和算法:使用Java进行深入研究”是最好的开始。 (P.S. — If you are serious about improving your Algorithms skills, I think the Data Structures and Algorithms: Deep Dive Using Java is the best one to start with.)

翻译自: https://www.freecodecamp.org/news/how-to-implement-a-binary-search-algorithm-in-java-without-recursion-67d9337fd75f/

java实现递归算法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值