Searching Alogrithms - PowerPoint PPT Presentation

1 / 18
About This Presentation
Title:

Searching Alogrithms

Description:

For most tasks (sorting an array, searching for an element, etc), there is more ... search or sort you use, since its not going to be a noticeable wait anyways. ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 19
Provided by: jonc7
Category:

less

Transcript and Presenter's Notes

Title: Searching Alogrithms


1
Searching Alogrithms
  • with Preconditions, Postconditions, and Assertions

2
Searching Algorithms
  • An algorithm is a way to solve a problem
  • For most tasks (sorting an array, searching for
    an element, etc), there is more than one way to
    solve a problem
  • To find an element in an array, we will look at
    three different algorithms
  • Sequential Search
  • Binary Search
  • Hashing (we won't do today, since it requires
    discussion about the Hashtable class, which we'll
    get to later on in the year. It is really more of
    a way to store elements that makes finding them
    easier than it is a searching algorithm)

3
Iterative Algorithms
  • An iterative algorithm is one that uses loops
    (aka iteration) to arrive at the solution.
  • Both of the searching algorithms we will look at
    today are iterative next class, we will look at
    another possibility

4
Disclaimer
  • When we talk about searching/sorting algorithms,
    we are talking about finding a value in a
    collection, like an Array or ArrayList.
  • All the examples today will be with Arrays of
    primitive data types, but using an Array or
    ArrayList of Objects that implement the
    Comparable interface would work the same way
  • For small collections, it really doesn't matter
    which search or sort you use, since its not going
    to be a noticeable wait anyways. Still, it's good
    to know what different algorithms are out there,
    and it gives us something to talk about when we
    discuss runtimes and Big Oh later

5
Iterative (using loops)Search Algorithms
6
Iterative Sequential Search
  • IdeaIf you have a collection and you want to
    see if it contains an element, start at index 0
    and go down the line until you find it, then
    return the index. If you get to the end and
    haven't found it, return -1 to indicate "not
    found".

7
Iterative Binary Search
  • IdeaIf you have a ALREADY SORTED collection and
    you want to see if it contains an element
  • Start with a counter variable min set to 0, and a
    max variable set to the last index in the array
  • While min is less than or equal to max
  • Set a mid variable to the index in the middle of
    min and max
  • If the element at mid is equal to what you're
    searching for, return mid
  • Else if the element at mid is gt what you're
    searching for, change max mid - 1
  • Else if the element at mid is lt what you're
    searching for, change min mid 1
  • If you exit the loop, return -1 for not found.

8
Preconditions
9
Preconditions and Postconditions
  • Binary Search only works if collection is already
    sorted. A big "if".
  • This concept that a method only works if a
    certain case is true is called a precondition
  • The idea that after a method is done, a condition
    must be true is called a postcondition
  • Although when you write the kind of programs we
    do in class, we often just assume that your
    preconditions and postconditions are true, you
    can of course test for them, then throw an
    exception if they aren't

10
Preconditions and Postconditions
  • On the AP test, Pre and Postconditions are
    typically written as a comment above the method
  • //precondition cost gt 0 and title ! null
  • //postcondition Book object created
  • public Book(String title, String author, double
    cost)
  • if((costlt0) (title null))
  • throw new IllegalArgumentException()
  • else
  • ....

11
Preconditions and Postconditions
  • If the precondition of a method involves an input
    parameter, you are always supposed to use control
    statements and try...catch or throws to deal with
    the error, so that the user will be aware of the
    error made so they know what not to do
  • However, if the precondition involves a instance
    variable (non-public data field) or is in a
    non-public method, there is another reserved word
    in Java we can use to test pre and
    postconditions assert

12
Asserts
13
Assert
  • A big addition to Java 1.4 was the assert
    reserved word
  • As it sounds, assert will make sure that a
    boolean statement is true, and throw a
    AssertationError exception if it isn't.
  • The syntax is as follows
  • assert BooleanExpression
  • You can also add a String or object that will be
    printed out to give more feedback on what went
    wrong
  • assert BooleanExpression ClarifyingObjectOrExpre
    ssion

14
Assert
  • Let's say we have a BankAccount class with a
    private instance variable interestRate that
    should never be lt 0, no matter what the user does
    to the account. The following method might make
    sense
  • public double calculateInterest(double years)
  • if(yearslt0)
  • throw new IllegalArgumentException()
  • else
  • assert (interestRategt0) "Interest Rate
    "interestRate
  • return interestRateyears

15
Assert
  • Unlike with try...catch blocks and throws,
    asserts should just be used to catch things that
    should never happen.
  • It should just be used as a status check when
    debugging your code, checking for errors and
    trying to verify everything is always running
    correct
  • It should not be used as part of functionality in
    your code...for that, use throws
  • The reason asserts are so limited is because you
    have to tell the JVM that you want to run with
    them turned on in order for them to work. They
    are not made to be used by actual users, just the
    programmers testing the code

16
Turning on Asserts
  • From command line
  • Instead of java FileName, type java -ea FileName
  • From JCreator
  • Make sure you are set to use a JDK gt 1.4. Then,
    before you execute, go to Configure Options
    Select Tool Type Run Application, click
    "Default", click edit, click Parameters tab, and
    add -ea at the beginning of the Parameters text
    field.
  • From Eclipse
  • Window Preferences Java Compiler and set the
    Compiler Compliance Level to 1.4 or later (5.0,
    6.0, etc). Also check Use Default compliance
    settings. Then go to Run Run Configurations,
    click Java Application, select the file name, go
    to Arguments tab type -ea in the VM arguments box

17
The Arrays/Collections classes in the API
  • The Arrays class is filled with static methods
    you can use with arrays
  • //precondition arr is sortedpublic static int
    binarySearch(double arr, double key)
  • The Collections class is similarly filled with
    static methods you can use with ArrayLists
  • //precondition list is sortedpublic static int
    binarySearch(List list, Object key)

18
Assignment
  • Inside of a new class called SearchMethods, make
    the following methods that work on either a
    Comparable or aArrayListsltComparablegt (your
    choice)
  • an iterative Sequential Search
  • an iterative Binary Search
Write a Comment
User Comments (0)
About PowerShow.com