生活随笔
收集整理的這篇文章主要介紹了
二分查找实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
二分查找實(shí)現(xiàn)
1.調(diào)用Arrays中的binarySearch方法即可實(shí)現(xiàn)
【使用前提:數(shù)組必須為升序排列】
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("對應(yīng)的索引為:"+index1
);int index2
= Arrays
.binarySearch(arr
, 11);System
.out
.println("對應(yīng)的索引為:"+index2
);}
}打印結(jié)果:
-----------------------------------------------------
對應(yīng)的索引為:
3
對應(yīng)的索引為:
-11
2.其底層代碼實(shí)現(xiàn)邏輯為:
【使用前提:數(shù)組必須為有序排列,下面為升序版,如果為降序則將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
+"對應(yīng)的索引為"+index
);}else {System
.out
.println("該數(shù)組中沒有該元素");}}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;}
}
總結(jié)
以上是生活随笔為你收集整理的二分查找实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。