Outline



queue implementation strategies reminder



naive linked list implementation of queues



linked list implementation of queues



runtime and space



actual runtime



implementation comparison



Binary Search (reminder)



recursive binary search

// return -1 if not found, or the index of the element if found
public int searchArray(T value, T a[], int firstIndex, int lastIndex) {
  int numElements = lastIndex - firstIndex + 1;
  if (numElements < 1) {
    return -1;
  }

  // assert(numElements > 0)
  int middle = numElements / 2 + firstIndex;
  if (value.compareTo(a[middle]) == 0) {  // found!
    return middle;
  }
  if (numElements == 1) {  // firstIndex == middle == lastIndex
    return -1;           // not a match
  }
  // assert(numElements > 1), so firstIndex < middle < lastIndex
  // assert(value.compareTo(a[middle]) != 0)
  if (value.compareTo(a[middle]) < 0) {  // in the first half of the array
    return searchArray(value, a, firstIndex, middle - 1);
  } else {                                  // in the second half of the array
    return searchArray(value, a, middle + 1, lastIndex);
  }
  // assert: cannot reach this point, must have returned somewhere above
}



maintaining a sorted array



trees



Tree properties



Tree properties exercise



more tree definitions



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