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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392673.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django 入门项目案例开发(中)

关注微信公众号&#xff1a;FocusBI 查看更多文章&#xff1b;加QQ群&#xff1a;808774277 获取学习资料和一起探讨问题。 昨天已经描述了如何搭建Django的开发环境&#xff0c;今天描述业务流程&#xff0c;具体我们要实现一个什么样的业务&#xff1b; 以下的业务都是假设的…

纵横公路造价软件学习_通辽分公司组织开展2020年 养护工程造价预算培训

为进一步提高养护员工业务水平和业务素质&#xff0c;提升熟练掌握信息化公路工程造价预算&#xff0c;11月5日&#xff0d;11月8日期间,通辽分公司组织开展了2020年养护工程造价预算培训。养护科全体人员、基层所站统计人员共计16人参加培训。本次培训邀请了纵横公路工程造价管…

java 生成二维码

一步一步用 java 设计生成二维码 转至 http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html 在物联网的时代&#xff0c;二维码是个很重要的东西了&#xff0c;现在无论什么东西都要搞个二维码标志&#xff0c;唯恐落伍&#xff0c;就差人没有用二维码识别了。也许有一天生分…

leetcode 922. 按奇偶排序数组 II(双指针)

给定一个非负整数数组 A&#xff0c; A 中一半整数是奇数&#xff0c;一半整数是偶数。 对数组进行排序&#xff0c;以便当 A[i] 为奇数时&#xff0c;i 也是奇数&#xff1b;当 A[i] 为偶数时&#xff0c; i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。 示例&a…

机器学习 深度学习 ai_如何突破AI炒作成为机器学习工程师

机器学习 深度学习 aiI’m sure you’ve heard of the incredible artificial intelligence applications out there — from programs that can beat the world’s best Go players to self-driving cars.我敢肯定&#xff0c;您已经听说过令人难以置信的人工智能应用程序-从可…

arcgis插值不覆盖区划图_ArcGIS绘图—空气质量站点数据插值绘制等值线图

作者&#xff1a;吴琳&#xff1b;陈天舒&#xff0c;山东大学环境科学&#xff08;大气化学&#xff09;博士在读数据&#xff08;Excel格式&#xff09;&#xff1a;多站点污染物数据&#xff08;国&#xff0c;省&#xff0c;市控点&#xff09;&#xff0c;站点经纬度信息绘…

数字校验

1 function validNumber(fieldname,fielddesc){2 var value $.trim($("#key_"fieldname).val());3 var num /^([0-9.])$/;4 5 var flag num.test(value);6 if(!flag) {7 alert("【"fielddesc"】只能输入数字");8 …

JavaScript覆盖率统计实现

主要需求 1、 支持browser & nodejs 由于javascript既能够在浏览器环境执行&#xff0c;也能够在nodejs环境执行&#xff0c;因此须要能够统计两种环境下单元測试的覆盖率情况。 2、 透明、无缝 用户写单元測试用例的时候&#xff0c;不须要为了支持覆盖率统计多写代码&…

leetcode 328. 奇偶链表(双指针)

给定一个单链表&#xff0c;把所有的奇数节点和偶数节点分别排在一起。请注意&#xff0c;这里的奇数节点和偶数节点指的是节点编号的奇偶性&#xff0c;而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1)&#xff0c;时间复杂度应为 O(nodes)…

NSLog打印当前文件,当前函数,当前行数

NSLog(”%s, %s, %d”, __FILE__, __FUNCTION__, __LINE__); 转载于:https://www.cnblogs.com/shenfei2031/archive/2011/08/06/2129636.html

单元格内容分列多行_姓名太多,放在一列打印时浪费纸张,可以分成多行多列打印...

在日常工作中&#xff0c;往往会碰到这种情况(如下图)&#xff1a;只有一列数据&#xff0c;而且比较多&#xff0c;如果打印起来就浪费纸张&#xff0c;然后复制、粘贴把表格变成几列&#xff0c;方便打印。今天小编和大家分享不用复制、粘贴&#xff0c;就能快速完成一列分成…

caesar加密_如何编写Caesar密码:基本加密简介

caesar加密by Brendan Massey由布伦丹梅西(Brendan Massey) The Caesar Cipher is a famous implementation of early day encryption. It would take a sentence and reorganize it based on a key that is enacted upon the alphabet. Take, for example, a key of 3 and th…

Java中接口、抽象类与内部类学习

2019独角兽企业重金招聘Python工程师标准>>> Java中接口、抽象类与内部类学习 接口与内部类为我们提供了一种将接口与实现分离的更加结构化的方法。 抽象类和抽象方法 抽象方法&#xff1a;仅有声明而没有方法体。 抽象类&#xff1a;包含一个或多个抽象方法的类&am…

leetcode 402. 移掉K位数字(贪心算法)

给定一个以字符串表示的非负整数 num&#xff0c;移除这个数中的 k 位数字&#xff0c;使得剩下的数字最小。 注意: num 的长度小于 10002 且 ≥ k。 num 不会包含任何前导零。 示例 1 : 输入: num “1432219”, k 3 输出: “1219” 解释: 移除掉三个数字 4, 3, 和 2 形成…

javascript 自定义Map

迁移时间&#xff1a;2017年5月25日08:24:19 Author:Marydon 三、自定义Map数据格式 需特别注意的是&#xff1a; js中没有像java中的Map数据格式&#xff0c;js自带的map()方法用于&#xff1a;返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。 map()使…

gif分解合成_如何通过分解和合成使复杂的问题更容易

gif分解合成Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“发现功能JavaScript”被BookAuthority评为最佳新功能编程书籍之一 &#xff01; Our natural way of dealing with complexity is to break it in…

vs2005 新建项目一片空白

最近在研究 workflow fundation ,但是在安装了他的extensions之后&#xff0c;发现VS2005 新建项目一片空白&#xff0c;除开workflow其他的项目模板全部丢失&#xff0c;新建项目对话框中空空如也。查阅资料后发现&#xff0c;可以通过 命令 devenv.exe /InstallVSTemplates 来…

docker导入镜像 liunx_docker扫盲?面试连这都不会就等着挂吧

推荐阅读&#xff1a;java喵&#xff1a;6大面试技能树&#xff1a;JAVA基础JVM算法数据库计算机网络操作系统​zhuanlan.zhihu.com一只Tom猫&#xff1a;都是“Redis惹的祸”&#xff0c;害我差点挂在美团三面&#xff0c;真是“虚惊一场”&#xff01;​zhuanlan.zhihu.com现…

crontab里shell脚本将top信息写入文件

crontab里shell脚本将top信息写入文件&#xff1a; 注&#xff1a; 1、top -n 1代表执行1次退出&#xff08;默认top是不退出的&#xff09;,-d 1代表每1秒执行1次 2、crontab里需加/bin/bash # crontab -e */5 * * * * /bin/bash /usr/local/bin/top.sh # vi top.sh #!/bin/ba…

leetcode 1030. 距离顺序排列矩阵单元格(bfs)

给出 R 行 C 列的矩阵&#xff0c;其中的单元格的整数坐标为 (r, c)&#xff0c;满足 0 < r < R 且 0 < c < C。 另外&#xff0c;我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。 返回矩阵中的所有单元格的坐标&#xff0c;并按到 (r0, c0) 的距离从最小到…