生活随笔
收集整理的這篇文章主要介紹了
二分查找实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二分查找實現
1.調用Arrays中的binarySearch方法即可實現
【使用前提:數組必須為升序排列】
public class Demo1 {public static void main(String
[] args
) {int[] arr
= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int key
= 4;int index1
= Arrays
.binarySearch(arr
, 4);System
.out
.println("對應的索引為:"+index1
);int index2
= Arrays
.binarySearch(arr
, 11);System
.out
.println("對應的索引為:"+index2
);}
}打印結果:
-----------------------------------------------------
對應的索引為:
3
對應的索引為:
-11
2.其底層代碼實現邏輯為:
【使用前提:數組必須為有序排列,下面為升序版,如果為降序則將start和end做替換】
public class Demo1 {public static void main(String
[] args
) {int []arr
={1,2,3,4,5,6,7,8,9,10};int key
=4;int index
= getbinarySerach(arr
, key
);if(index
!=-1){System
.out
.println(key
+"對應的索引為"+index
);}else {System
.out
.println("該數組中沒有該元素");}}private static int getbinarySerach(int[] arr
, int key
) {int start
=0;int end
=arr
.length
-1,mid
;while (start
<=end
) {mid
=(end
+start
)>>1;if(arr
[mid
]<key
){start
=mid
+1;}else if(arr
[mid
]>key
){end
=mid
-1;}else {return mid
;}}return -1;}
}
總結
以上是生活随笔為你收集整理的二分查找实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。