順序尋找JAVA實現 設定哨兵

來源:互聯網
上載者:User

標籤:

/** * 順序尋找,設定哨兵 * 待尋找數組:a[n] * 待尋找元素:key *  * 方法: * b[n+1],其中,b[0]存放key,b[1]至b[n]存放a[0]至a[n-1]的元素 * 將b[n]從後向前掃描,如果尋找成功,返回元素在數組b中的下標,從1開始;如果尋找失敗,返回0 *  * 設定哨兵的好處:避免了每次迴圈後都要檢查數組下標是否越界 * @author kpp * */public class SequenSearch {    public static void main(String[] args) {        // TODO Auto-generated method stub        int data[] = {38,65,97,176,213,227,49,78,34,12,164,11,18,1};        int key = 2;        int index = search(data,key);        if(index == 0){            System.out.println("尋找失敗");        }else{            index = index - 1;            System.out.println("尋找成功,key在數組的第"+index+"個位置(從0開始)");        }            }    /**     *      * @param a    待尋找數組     * @param key  待尋找元素     * @return     如果尋找成功,返回元素在數組b中的下標,從1開始;如果尋找失敗,返回0     */    private static int search(int a[],int key){        int len = a.length;        int b[] = new int[len+1];        b[0] = key;        System.arraycopy(a, 0, b, 1, len);                int i = len;        while(key != b[i]){            i--;        }        return i;    }}

 

順序尋找JAVA實現 設定哨兵

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.