CS 101 Lecture 29 - Searching, Complexity of Algorithms

Class Examples:

  1. An iterative method for finding 'num' in an unordered array (linear search):
      /*
       * Search for num in array.  Return the index of the number, or
       * -1 if it is not found.
       */
      int search(int[] array, int num) {
        for (int index = 0; index < array.length; index++) {
          if (array[index] == num) {
            return index;
          }
        }
        return -1;
      }
    

  2. A recursive linear search method:
      /*
       * Search for num in array recursively. Return the index of the number, or
       * -1 if it is not found.
       */
      int recSearch(int[] array, int num, int start) {
        if (start >= array.length) {
          return -1;
        } else if (array[start] == num) {
          return start;
        } else {
          return recSearch(array, num, start + 1);
        }
      }
    

  3. A recursive method for searching an ordered list (binary search):
      /*
       * Binary Search for num in array.  Pass in the low and high 
       * indices of the array for the range in which the number may
       * still occur.  Return the index of the number, or -1 if it
       * is not found.
       */
      int binarySearch(int[] array, int num, int low, int high) {
       if (low > high) {
          return -1;
        } else {
          int mid = (low + high) / 2;
          if (array[mid] == num) {
            // num is same as middle number
            return mid;
          } else if (num < array[mid]) {
            // num is smaller than middle number
            return binarySearch(array, num, low, mid - 1);
          } else {
            // num is larger than middle number
            return binarySearch(array, num, mid + 1, high);
          }
        }
      }