折半尋找,

來源:互聯網
上載者:User

折半尋找,

小知識點,初學者易懂,備忘清晰,簡單明了。要求:   1. 在有序的情況下,升序和降序。   2.求某個元素在數組中的位置,如果不存在返回-1。
//包名package test1111;public class Demo2 {public static void main(String[] args) {//首先是一個排好序的數組(升序或降序)int[] arr = {11,23,40,45,59,65,99};//尋找 數字45int index = getIndex(arr, 65);//獲得查到的數字下標值System.out.println("index="+index);//index=5}public static int getIndex(int[] arr,int key){int minIndex = 0;//最小下標int maxIndex = arr.length-1;//最大下標int midIndex = (maxIndex + minIndex)/2;//中間下標while(key != arr[midIndex]){//當中間值和key不等的時候進入迴圈重新獲得一組數字if(key > arr[midIndex]){//key大於中間值,獲得新值最小下標等於中間下標+1minIndex = midIndex + 1;}else{//key小於中間值,獲得最大下標等於中間下標-1maxIndex = midIndex - 1;}if(maxIndex < minIndex){//最大下標小於最小下標 證明值不存在return -1;//若果不存在返回-1}//新的一組數位中間下標midIndex = (maxIndex + minIndex)/2;}return midIndex;//始終返回的都是數組中間那個數的下標}}

  

聯繫我們

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