Java-数据结构与算法-二分查找法
生活随笔
收集整理的這篇文章主要介紹了
Java-数据结构与算法-二分查找法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.二分查找法思路:不斷縮小范圍,直到low <= high
2.代碼:
1 package Test; 2 3 import java.util.Arrays; 4 5 public class BinarySearch { 6 7 public static void main(String[] args) { 8 int [] a = {1,5,7,9,11,12,16,20}; 9 int target = 16; 10 //System.out.println(Arrays.binarySearch(a, target)); 11 System.out.println(binarySearch(a, target)); 12 } 13 14 public static int binarySearch(int [] a, int target){ 15 int low = 0; 16 int high = a.length - 1; 17 18 while (low <= high) { 19 int mid = (low + high) >>> 1; 20 int midVal = a[mid]; 21 22 if (midVal < target) 23 low = mid + 1; 24 else if (midVal > target) 25 high = mid - 1; 26 else 27 return mid; // key found 28 } 29 return -(low + 1); // key not found. 30 } 31 }3.結(jié)果:6
轉(zhuǎn)載于:https://www.cnblogs.com/shamgod/p/4604376.html
總結(jié)
以上是生活随笔為你收集整理的Java-数据结构与算法-二分查找法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好看的UI界面
- 下一篇: MongoDB Replication