Algorithms and OOD (CSC 207 2014S) : EBoards

CSC207.01 2014S, Class 19: Linear and Binary Search




Upcoming Work

Questions on the exam

Analyzing binary search

Functions as parameters

When you write a searching or sorting algorithm, you often want a function as a parameter

;;; Find the first ok thing in the list
(define search
  (lambda (lst ok?)
    (if (null? lst)
        (if (ok? (car lst))
            (car lst)
            (search (cdr lst) ok?)))))

Java does not (currently) allow functions as first class values. But it does allow objects/interfaces as first-class values. Instead of passing in a function, we pass in an object that contains that function/method.

public interface Predicate
  public boolean ok(Object o);
} // interface Predicate

public class LessThanTwo 
  implements Predicate
  public boolean ok(Object o)
    return (o instanceof Number) &&
           (((Number) o).doubleValue < 2.0);
  } // ok

} // class LessThanTwo

Great idea in Scheme: Anonymous functions

(search students (lambda (student) (and (here? student) (awake? student))))

Java has anonymous classes! We'll look at them later.

What's the difference between Java's Comparator and Comparable?

Generics (e.g., Comparator<T>)

See forthcoming reading.


What's wrong with the following?

if (vals[mid] > val)
  vals = Arrays.copyOfRange(vals, 0, mid);
else if (vals[mid] < val)
  vals = Arrays.copyOfRange(vals, mid+1, vals.length);

int mid = lower + upper/2;

int mid = (lower + upper)/2;

I'm proud of you.

Copyright (c) 2013-14 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.