演算法——二分尋找演算法(Java實現)__編碼

來源:互聯網
上載者:User

1、前提:二分尋找的前提是需要尋找的數組必須是已排序的,我們這裡的實現預設為升序

2、原理:將數組分為三部分,依次是中值(所謂的中值就是數組中間位置的那個值)前,中值,中值後;將要尋找的值和數組的中值進行比較,若小於中值則在中值前面找,若大於中值則在中值後面找,等於中值時直接返回。然後依次是一個遞迴過程,將前半部分或者後半部分繼續分解為三部分。可能描述得不是很清楚,若是不理解可以去網上找。從描述上就可以看出這個演算法適合用遞迴來實現,可以用遞迴的都可以用迴圈來實現。所以我們的實現分為遞迴和迴圈兩種,可以根據代碼來理解演算法

3、實現:代碼如下

package org.cyxl.algorithm.search;/** * 二分尋找 * @author cyxl * */public class BinarySearch {private int rCount=0;private int lCount=0;/** * 擷取遞迴的次數 * @return */public int getrCount() {return rCount;}/** * 擷取迴圈的次數 * @return */public int getlCount() {return lCount;}/** * 執行遞迴二分尋找,返回第一次出現該值的位置 * @param sortedData已排序的數組 * @param start開始位置 * @param end結束位置 * @param findValue需要找的值 * @return值在數組中的位置,從0開始。找不到返回-1 */public int searchRecursive(int[] sortedData,int start,int end,int findValue){rCount++;if(start<=end){//中間位置int middle=(start+end)>>1;//相當於(start+end)/2//中值int middleValue=sortedData[middle];if(findValue==middleValue){//等於中值直接返回return middle;}else if(findValue<middleValue){//小於中值時在中值前面找return searchRecursive(sortedData,start,middle-1,findValue);}else{//大於中值在中值後面找return searchRecursive(sortedData,middle+1,end,findValue);}}else{//找不到return -1;}}/** * 迴圈二分尋找,返回第一次出現該值的位置 * @param sortedData已排序的數組 * @param findValue需要找的值 * @return值在數組中的位置,從0開始。找不到返回-1 */public int searchLoop(int[] sortedData,int findValue){int start=0;int end=sortedData.length-1;while(start<=end){lCount++;//中間位置int middle=(start+end)>>1;//相當於(start+end)/2//中值int middleValue=sortedData[middle];if(findValue==middleValue){//等於中值直接返回return middle;}else if(findValue<middleValue){//小於中值時在中值前面找end=middle-1;}else{//大於中值在中值後面找start=middle+1;}}//找不到return -1;}}

4、測試代碼

package org.cyxl.algorithm.search.test;import org.cyxl.algorithm.search.BinarySearch;import org.junit.Test;public class BinarySearchTest {@Testpublic void testSearch(){BinarySearch bs=new BinarySearch();int[] sortedData={1,2,3,4,5,6,6,7,8,8,9,10};int findValue=9;int length=sortedData.length;int pos=bs.searchRecursive(sortedData, 0, length-1, findValue);System.out.println("Recursice:"+findValue+" found in pos "+pos+";count:"+bs.getrCount());int pos2=bs.searchLoop(sortedData, findValue);System.out.println("Loop:"+findValue+" found in pos "+pos+";count:"+bs.getlCount());}}

5、總結:這種尋找方式的使用場合為已排序的數組。可以發現遞迴和迴圈的次數是一樣的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.