Binary Search


Recursive binary search


/* Returns -1 if not found, or the index of the element if found */
public Type binarySearch (Type value, Type array [], int first, int last) {
  int count = last - first + 1;
  if (count < 1) {
    return null;
  } else if (count == 1) {
    return value.compareTo (array [first]) == 0) array [first] ? null;
  } else { // assert (count > 0)
    int middle = first + count / 2;
    if (value.compareTo (array [middle] < 0) { // in the first half of the array
      return binarySearch (value, array, first, middle - 1);
    } else {               // in the second half of the array
      return binarySearch (value, array, middle + 1, last);
    }
  }
}


Maintaining a sorted array


Trees


Tree definitions


Tree properties exercise


More tree definitions


Special trees


Binary search trees


Binary tree traversals


Expression trees


Binary search tree properties


Binary search tree add operation


Binary search tree remove operation


Removing a node that has both subtrees


Binary node class


Binary search tree class


Binary search tree implementation


Binary search tree get operation


Binary search tree add operation


Adding a node to a binary search tree


Binary search tree remove operation


Removing a node with both subtrees


Traversing the search tree


Efficiency of binary search tree operations


Databases and search keys