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.pswp.cn/news/392673.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392673.shtml
英文地址,請注明出處:http://en.pswp.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) 的距離從最小到…