Computer Science Examples
Searching Methods

// Method that uses a boolean to help with the search.
 public Node searchList1 (String keyId)
 {
      int location = 0;
      boolean found = false;

      while (!found && (location < listSize))
           if (list [location].getId ().equals (keyId)) found = true;
           else location ++;
      if (found) return list [location];
      else return null;
 } // method searchList

 // Method that uses ‘lazy evaluation’ in the while loop condition when searching for a Node.
 public Node searchList2 (String keyId)
 {
      int location = 0;

      while ((location < listSize) && !(list[location].getId ().equals (keyId)))
           location ++;
      return list[location];
 }

 // Non-recursive binary search.
public Node searchList3 (String keyId)
 {
      int low = 0, high = listSize-1, mid = 0;
      boolean found = false;

      while ((low <= high) && (found == false))
      {
           mid = (low + high) / 2;
           if (list [mid].getId ().equals (keyId)) found = true;
           else
           {
                if (list [mid].getId ().compareTo (keyId) < 0) low = mid + 1;
                else  high = mid - 1;
           }
      }
      if (found == true) return list[mid];
      else return null;
 } // method searchList3