binary search arraylist algorithm

Solutions on MaxInterview for binary search arraylist algorithm by the best coders in the world

showing results for - "binary search arraylist algorithm"
Leon
02 Sep 2020
1public static int binarySearch(int[] elements, int target) {
2      int left = 0;
3      int right = elements.length - 1;
4      while (left <= right)
5      {
6         int middle = (left + right) / 2;
7         if (target < elements[middle])
8         {
9            right = middle - 1;
10         }
11         else if (target > elements[middle])
12         {
13            left = middle + 1;
14         }
15         else {
16            return middle;
17         }
18       }
19       return -1;
20   }