binary search java arraylist code example

Example 1: binary search arraylist algorithm

public static int binarySearch(int[] elements, int target) {
      int left = 0;
      int right = elements.length - 1;
      while (left <= right)
      {
         int middle = (left + right) / 2;
         if (target < elements[middle])
         {
            right = middle - 1;
         }
         else if (target > elements[middle])
         {
            left = middle + 1;
         }
         else {
            return middle;
         }
       }
       return -1;
   }

Example 2: java search arraylist

//create ArrayList
ArrayList<String> arrayList = new ArrayList<String>();
//add item to ArrayList
arrayList.add("item");
//check if ArrayList contains item (returns boolean)
System.out.println(arrayList.contains("item"));
//remove item from ArrayList
arrayList.remove("item");

Tags:

Java Example