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
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("item");
System.out.println(arrayList.contains("item"));
arrayList.remove("item");