折半尋找法—C語言實現

來源:互聯網
上載者:User

/*******************************************************************************************<br />** 函數名稱: HalfFindElement()<br />** 作 者: 張月華<br />** 版 本: 1.0.0<br />** 日 期: 2011-6-16<br />** 功能描述: 折半尋找,返回元素的位置(從0開始計數,和數組下標一致)<br />** 被本函數調用的函數清單:<br />** 調用本函數的函數清單: 1. main()<br />** 被訪問的表: 無<br />** 被修改的表 : 無<br />** 輸 入:<br /> int array_in[] --- 輸入數組,升序排列<br />int element_amount --- 元素個數<br />int key_in --- 欲尋找的關鍵字<br />** 輸 出: 無<br />** 返 回 值: 尋找到 -- 關鍵字的位置(標號和數組下標一致)<br /> 沒找到 -- 返回-1</p><p>** 其 他:<br />** 修改曆史: </p><p>1. 修改時間:<br /> 修 改 者:<br /> 版 本:<br /> 修改簡述:<br /> 2. ......<br />*********************************************************************************************/</p><p>int HalfFindElement(int array_in[],int element_amount,int key_in) /* array_in[]是升序數組 */<br />{<br /> int mid; /* 折半尋找的中間位置 */<br />int top = 0;<br />int bottom = element_amount - 1;<br />int is_find = 0; /* 尋找到標識符。找到=1,否則=0 */<br />int local ; /* 找到的元素的位置 */</p><p>if ((key_in < array_in[0]) || (key_in > array_in[element_amount - 1]) ) /* 再迴圈開始前就判斷 */<br /> {<br />local = -1; /* 標記位置 */<br /> is_find = 0; /* 沒找到 */<br /> }</p><p>while ( (is_find == 0) && (top <= bottom))<br />{<br />mid = (top + bottom) / 2; </p><p> if (key_in == array_in[mid]) /* 找到了 */<br /> {<br /> local = mid; /* 標記位置 */<br /> is_find = 1; /* 找到 */<br /> }</p><p>else<br />if (key_in < array_in[mid])<br />{<br />bottom = mid - 1;<br />}<br />else<br />{<br />top = mid + 1;<br />}<br />}</p><p>if ((0 == is_find) || ( -1 == local)) /* 傳回值 */<br />{<br />return -1;<br />}</p><p>else</p><p>return local; /* 返回位置 */</p><p>}<br />

聯繫我們

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