java实现递归算法

by javinpaul

由javinpaul

流行的二进制搜索算法的迭代实现,用于在排序数组中查找元素。 (An Iterative implementation of the popular binary search algorithm to find an element in a sorted array.)

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实现递归算法

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

  1. java 正则表达式 开头_如何在Java中修复表达式的非法开头

    java 正则表达式 开头 您是否遇到过这个令人难以置信的错误,想知道如何解决它? 让我们仔细阅读一下,研究如何解决表达式Java非法开头错误. 这是一个动态错误,这意味着编译器会发现某些不符合Jav ...

  2. java soap 头_如何在Java中添加Soap标头

    我有一个来自oracle的NO.net Web服务,要访问,我需要添加soap标头.如何在Java中添加soap标头? Authenticator.setDefault(new ProxyAuthen ...

  3. java jcombobox长度_如何在JToolBar中设定JComboBox的大小?

    如何在JToolBar中设定JComboBox的大小? 我设计了一个JToolBar,并且在上边添加了一个JComboBox,可是我发现这个JComboBox长度无法控制,它将JToolBar上剩余空 ...

  4. java 全局数组_如何在Java中声明全局数组?

    我有一个程序在Java中乘以两个矩阵.我在全局错误声明中发现了一些错误. 这里是我的代码如何在Java中声明全局数组? import java.util.Scanner; /**WAP in Java ...

  5. java 判断数字_如何在java中判断一个字符串是否是数字

    前言 数字在某些领域经常用字符串来进行表示和传递.那么我们如何判断一个字符串是否是数字呢?今天我们来探讨一下这个话题. 空字符和null 首先我们可以很清晰的知道空字符""和nul ...

  6. java插入图片_如何在java窗体程序中添加图片

    打开eclipse,创建一个java工程项目,创建完后在src下新建一个类Window,由于要插入图片,所以还在工程目录下创建一个文件夹imgs,里面放了一张60*60的图片,创建后的工程目录和图片, ...

  7. java安卓计时器_如何在android中设置计时器

    通过java.util.Timer和java.util.TimerTask使用计时器的标准Java方法在Android中运行良好,但是你应该知道这个方法创建了一个新线程. 您可以考虑使用非常方便的Ha ...

  8. java cpu监控_如何在Java中监视计算机的CPU,内存和磁盘使用情况?

    问题 我想用Java监视以下系统信息: 当前CPU使用率**(百分比) 可用内存*(免费/总计) 可用磁盘空间(空闲/总计)*请注意,我的意思是整个系统可用的总内存,而不仅仅是JVM. 我正在寻找一种 ...

  9. java redis 缓存_如何在 Java 中实现一个 redis 缓存服务

    缓存服务的意义 为什么要使用缓存?说到底是为了提高系统的运行速度.将用户频繁访问的内容存放在离用户最近,访问速度最快的地方,提高用户的响应速度.一个 web 应用的简单结构如下图. web 应用典型架 ...

最新文章

  1. Mybatis框架的操作步骤和细节处理
  2. 邮件服务器fixpost服务(1)
  3. Kubernetes之集群环境搭建
  4. [数据结构]前缀、中缀、前缀表达式
  5. mongodb查询不等于某个字段_Oracle单表查询多字段,不使用*
  6. 利用后中遍历结果,重构二叉树
  7. 下载程序到STC单片机的操作步骤
  8. C语言编译插桩,深度解析编译插桩技术(二)AspectJ
  9. 开发erp管理系统的好处
  10. wps建立的文件后缀名为docx,写在里面的东西还不允许保存
  11. 这几款手机浏览器真的牛,比夸克更好用
  12. 日语动词里的未然形、连用形、终止形、连体形、假定形、命令形、推量形各代表的意思
  13. SGX初始化中ELF文件解析
  14. 安卓手机管理_彻底解决安卓手机通知管理难题,顺便还实现了聊天消息防撤回!?
  15. 祝福我的家人朋友永远平安健康
  16. 常见的协议的协议号及端口
  17. 滴滴实时计算平台在运营监控方面的应用
  18. 将webApp或者H5页面打包成App
  19. grid_map(一):grid_map学习
  20. HEP惠普SN3600B,H3C新华三CN3360B光纤交换机调试配置方法

热门文章

  1. WinPcap笔记(3):获取已安装设备的详细信息
  2. WinPcap笔记(1):VisualStudio2015配置WinCap
  3. java基础常问面试题,面试必问
  4. RocketMQ消息丢失场景及解决办法,已拿offer入职
  5. 保驾护航金三银四,妈妈再也不用担心我找工作了!
  6. 使用lt;jsp:includegt;,不想写死URL,动态生成URL的解决的方法
  7. Redis PHP连接操作
  8. [置顶] Java Socket实战之一 单线程通信
  9. selenium用法详解
  10. 数据挖掘的相关知识例子