Data Structures, Algorithms, - PowerPoint PPT Presentation

1 / 92
About This Presentation
Title:

Data Structures, Algorithms,

Description:

Data structures is concerned with the representation and manipulation of data. ... into unchecked runtime exceptions. */ MyInputException. package exceptions; ... – PowerPoint PPT presentation

Number of Views:158
Avg rating:3.0/5.0
Slides: 93
Provided by: Agam
Category:

less

Transcript and Presenter's Notes

Title: Data Structures, Algorithms,


1
Data Structures, Algorithms, Applications
  • John Barr

2
What The Course Is About
  • Data structures is concerned with the
    representation and manipulation of data.
  • All programs manipulate data.
  • So, all programs represent data in some way.
  • Data manipulation requires an algorithm.

3
What The Course Is About
  • Algorithm design methods needed to develop
    programs that do the data manipulation.

4
Prerequisites
  • Java
  • Asymptotic Complexity
  • Big Oh, Theta, and Omega notations

5
Web Site
  • www.ithaca.edu/barr/Student/CS311

6
Assignments
  • Submission procedures
  • Assignment guidelines

7
Source Codes
  • Read download and use instructions.
  • Must have Java 1.2 or higher.
  • See ProgramIndex.htm, AllNames.html and other
    html files produced by Javadoc for Java codes.
  • I will use the java 2 JDK. You can develop in
    anything, but it must run in the JDK.

8
Grades
  • 25 for problem sets/programs (10)
  • 40 for tests (3 tests see web)
  • 30 for projects
  • 5 participation

9
Organization of Text
  • Three parts
  • Part I Chapters 1-4, Background
  • Part 2 Chapters 5-17, Data Structures
  • Part 3 Chapters 18-22, Algorithms
  • Each chapter concepts applications

10
Java
  • Topics
  • Packages
  • Inheritance
  • Method Overriding
  • Exceptions
  • Generic Methods
  • Interfaces, Abstract Classes

11
Java
  • Exception Classes
  • EmptyQueueException
  • MyInputException
  • UndefinedMethodException

12
MyInputException
  • Thrown by methods of class MyInputStream, defined
    in the book.
  • Javas standard input methods throw exceptions
    that are subclasses of IOException.
  • Thus must be declared in the throws clause of all
    methods that use std input.
  • MyInputException is a subclass of
    RunTimeException. Do not have to catch these
    exceptions.

13
MyInputException
  • / This exception is thrown when an input
  • exception occurs. It is used by
    MyInputStream
  • to convert checked exceptions such as
  • FileNotFoundException and EOFException
  • into unchecked runtime exceptions. /

14
MyInputException
  • package exceptions
  • public class MyInputException
  • extends RuntimeException
  • public MyInputException()
  • super()
  • public MyInputException(String message)
  • super(message)

15
MyInputStream
  • Catch exceptions of type IOException thrown by
    Javas input methods
  • Throws exceptions of type MyInputException

16
Generic Methods
  • Uses an interface class
  • Is not an interface itself
  • Can accept sub-classes that implement an
    interface class.

17
Generic Methods
  • Not possible for Java primitive types.
  • Use with subclasses of type Object
  • Must write wrapper classes for primitive types.

18
Generic Methods
  • / Swap the integers ai and aj. /
  • public static void swap(int a, int i, int
    j)
  • // Don't bother to check that indexes i and
    j
  • // are in bounds. Java will do this and
    throw
  • // an ArrayIndexOutOfBoundsException if i
    or
  • // j is out of bounds.
  • int temp ai
  • ai aj
  • aj temp

19
Generic Methods
  • / Generic method to swap the object
  • references ai and aj. /
  • public static void swap(Object a, int i,
    int j)
  • Object temp ai
  • ai aj
  • aj temp

20
Generic Methods
  • package misc
  • public class Abc
  • public static int abc(int a, int b, int c)
  • return abbc(ab-c)/(ab)4
  • public static void main(String args)
  • System.out.println(abc(2,3,4))

21
Generic Methods
  • package misc
  • public class Abc
  • public static float abc(float a, float b,
    float c)
  • return abbc(ab-c)/(ab)4
  • public static void main(String args)
  • System.out.println(abc(2,3,4))

22
Generic Methods
  • Problem with making a generic abc method
  • Not all objects can or or /
  • Need to restrict the objects that the generic
    method accepts.

23
Interfaces
  • A list of 0 or more static final data members
    (constants)
  • And 0 or more method headers with no
    implementation.
  • A class can implement 0 or more interfaces, but
    can only extend one class (or one abstract class)

24
Interfaces
  • Can define methods that have formal parameters
    whose data type is an interface
  • Cannot create instances of an interface
  • Instances of a class that implements an interface
    may be cast into the data type of the interface.

25
The Computable Interface
  • package utilities
  • / Interface to be implemented by all classes
  • that permit the standard arithmetic
    operations. /
  • public interface Computable
  • / _at_return this x /
  • public Object add(Object x)
  • / _at_return this - x /
  • public Object subtract(Object x)
  • / _at_return this x /
  • public Object multiply(Object x)

26
The Computable Interface (cont)
  • / _at_return quotient of this / x /
  • public Object divide(Object x)
  • / _at_return remainder of this / x /
  • public Object mod(Object x)
  • / _at_return this incremented by x /
  • public Object increment(Object x)
  • / _at_return this decremented by x /
  • public Object decrement(Object x)
  • / _at_return the additive zero element /
  • public Object zero()
  • / _at_return the multiplicative identity
    element /
  • public Object identity()

27
Generic Method abc
  • package misc
  • import wrappers.
  • import utilities.
  • public class GenericAbc
  • public static Computable abc(Computable a,
    Computable b, Computable c)
  • Computable t (Computable)
    a.add(b.multiply(c))
  • return (Computable) t.add(b.divide(c))
  • public static void main(String args)
  • MyInteger x, y, z
  • x new MyInteger(2)
  • y new MyInteger(3)
  • z new MyInteger(4)
  • System.out.println(abc(x, y, z))

28
The MyComparable Interface
  • package utilities
  • / Interface to be implemented by all classes
    that permit comparison between their objects.
    Comparable has only one method.
  • /
  • public interface MyComparable extends Comparable
  • / _at_return -1 if this lt x,
  • 0 if this x,
  • 1 if this gt x /
  • public int compareTo(Object x)
  • / _at_return true iff this lt x /
  • public boolean lessThan(Object x)
  • / _at_return true iff this lt x /
  • public boolean lessThanOrEqual(Object x)

29
The MyComparable Interface
  • / _at_return true iff this gt x /
  • public boolean greaterThan(Object x)
  • / _at_return true iff this gt x /
  • public boolean greaterThanOrEqual(Object x)
  • / _at_return true iff this x /
  • public boolean equals(Object x)

30
The Operable Interface
  • / Marker interface for classes that are
  • both Computable and Comparable. /
  • package utilities
  • public interface Operable extends Computable,
    Comparable

31
The Zero Interface
  • package utilities
  • / Interface to be implemented by all classes
  • that implement provide a zero value and test
    for zero. /
  • public interface Zero
  • public Object zero()
  • public boolean equalsZero()

32
The CloneableObject Interface
  • Cloning vs copying
  • X new currancy(3.42)
  • Y x
  • y.setValue(6.25)
  • System.out.println(x)
  • gtgt 6.25
  • Why?

33
The CloneableObject Interface
X new currancy(3.42)
x
3.42
34
The CloneableObject Interface
X new currancy(3.42)
x
y
Y x
3.42
35
The CloneableObject Interface
X new currancy(3.42)
x
y
Y x
y.setValue(6.25)
3.42
6.25
36
The CloneableObject Interface
X new currancy(3.42) Y x.clone() y.setValue(
6.25) System.out.println(x)
x
x
x
y
y
3.42
3.42
3.42
6.25
3.42
37
The CloneableObject Interface
  • package utilities
  • / Interface to be implemented by all classes
  • that implement the method clone. /
  • public interface CloneableObject extends
    Cloneable
  • public Object clone()

38
Wrapper Classes
  • Built-in in Java
  • Redefined in book to use books interfaces.

39
Integer Wrapper Class
  • / wrapper class for int /
  • package wrappers
  • import utilities.
  • import exceptions.
  • public class MyInteger
  • implements Operable, Zero, CloneableObject
  • // value of the integer
  • private int value

40
Integer Wrapper Class
  • // constructor methods
  • / MyInteger initialized to theValue /
  • public MyInteger(int theValue)
  • value theValue
  • / MyInteger initialized to 0 /
  • public MyInteger()
  • this(0)
  • / MyInteger initialized to s /
  • public MyInteger(String s)
  • throws NumberFormatException
  • value Integer.parseInt(s)

41
Integer Wrapper Class(partial)
  • / input from the given input stream /
  • public static MyInteger input(MyInputStream
    stream)
  • System.out.println("Enter an integer
    value")
  • return new MyInteger(stream.readInteger())
  • / make a clone /
  • public Object clone()
  • return new MyInteger(value)

42
Integer Wrapper Class
  • // Computable interface methods
  • / _at_return this x /
  • public Object add(Object x)
  • return new MyInteger
  • (value ((MyInteger) x).value)

43
Integer Wrapper Class
  • // Comparable interface method
  • / _at_return -1 if this lt x,
  • 0 if this x,
  • 1 if this gt x /
  • public int compareTo(Object x)
  • int y ((MyInteger) x).value
  • if (value lt y) return -1
  • if (value y) return 0
  • return 1

44
Integer Wrapper Class
  • // override Object.equals
  • / _at_return true iff this x /
  • public boolean equals(Object x)
  • return value ((MyInteger) x).value

45
Data Types and Methodsas paramters
  • Example. Class whose instances are 1-D arrays.
  • Method InputArray inputs n items, creates array
    of size n and stores elements into array.
  • Problem data type of elements is unknown until
    run time.

46
Data Types and Methodsas paramters
  • Solution make the data type a parameter,
    theClass.
  • Data type of theClass is Class (defined in
    java.lang)
  • Obtain a type by
  • Class typeOfInt int.class
  • Class typeofMyInteger MyInteger.class

47
Data Types and Methodsas paramters
  • Other information
  • Where to get data from (stnd input, file, etc)
  • How to input a type (e.g., to input an element of
    type Currency must read a sign, a dollar value, a
    cents value)
  • Solution
  • Pass in input stream as parameter
  • Require each data type implement a public static
    method input(MyInputStream stream)

48
Methods as paramters
  • package misc
  • import java.lang.reflect.
  • import wrappers.
  • import utilities.
  • public class Array1D
  • // instance data member
  • Object a

49
Methods as paramters
  • To get a reference to the input method of the
    desired class use
  • Java.lang.Class.getMethod(String name, Class
    parameterTypes)
  • Returns an object of type Method (defined in
    java.lang.reflect)
  • Name name of method we are looking for
  • parameterTypes signature of method Name.

50
Methods as paramters
  • To invoke the returned method, must use the class
    function
  • Method.invoke(instance, actual parameters)
  • Use null for first parameter if method invoking
    is static.
  • Second parameter must be an array of parameters.
  • getMethod and invoke throw exceptions that are
    not of a type that is a subclass of
    runtimeException, thus must catch or declare a
    throws.

51
/ input objects of type theClass and store in
an array / public void inputArray(Class
theClass, MyInputStream stream) try
// get the proper method to be used
to read in the values Class
parameterTypes MyInputStream.class
Method inputMethod theClass.getMethod("input",
parameterTypes) // input number of
elements and create an array of that size
System.out.println("Enter number of elements")
int n stream.readInteger() a
new Object n
52
// input the elements Object
inputMethodArgs stream for (int i
0 i lt n i)
System.out.println("Enter element " (i1))
ai inputMethod.invoke(null,
inputMethodArgs) catch
(Exception e) System.out.println(
e) throw new IllegalArgumentException("A
rray1D.inputArray")
53
Recursion
  • Recursive (mathematical) functions
  • Induction
  • Recursive methods

54
Recursive functionsfactorial f(n) n!
  • Base f(n) defined directly for some value(s) of
    n
  • Recursive component right side has a parameter
    less than n

55
Recursive functions
  • f(5) 5f(4) 20f(3) 60f(2) 120f(1)

56
Recursive functionsFibonacci numbers
  • f(4)

f(3)f(2) f(2)f(1)f(1) f(1)f(0)f(1)f(1)
3
57
Induction
  • Induction base claim is true for one or more
    base values of n
  • Induction hypothesis assume that claim is true
    for values of n from base through m, m is
    arbitrary number greater than the base
  • Induction step prove that claim is true for
    next value of n (ie, m1)

58
Induction
  • Induction base show true for n0.
  • Induction hypothesis assume that claim is true
    for m, 0 lt m lt n
  • Induction step prove for m1
  • Do it!

59
Induction
60
Induction
61
Recursive Methods
  • / _at_return n! /
  • public static int factorial(int n)
  • if (n lt 1)
  • return 1
  • else
  • return n factorial(n - 1)

62
  • public static Computable recursiveSum(Computable
    a, int n)
  • // Driver for true recursive method rsum.
  • count // for if-else statement
  • if (a.length gt 0)
  • return rSum(a, n)
  • else return null // no elements to sum
  • private static Computable rSum(Computable
    a, int n)
  • if (n 0)
  • count // for conditional and return
  • return (Computable) a0.zero()
  • else
  • count // for conditional, rSum
    invocation,
  • // add, and return

63
public class Permutation / perm(x, 0, n)
outputs all permutations of x0n / public
static void perm(Object list, int k, int m)
// Generate all permutations of listkm.
int i if (k m) // listkm has
one permutation, output it for (i 0 i
lt m i) System.out.print(listi)
System.out.println()
else // listkm has more than one
permutation // generate these recursively
for (i k i lt m i)
MyMath.swap(list, k, i) perm(list,
k1, m) MyMath.swap(list, k, i)

64
Permutations
a
b
c
a
b
c
c
a
a
b
b
c
a
a
b
b
c
c
a
b
c
a
b
c
a
b
b
c
a
c
65
TestingWhy?
  • Problem formal proofs not feasible

Problem Number of possible inputs to any
program is generally too large to test all of
them.
Result the objective of testing is not
to establish correctness, but to expose the
presence of errors.
66
Testing
  • Test set must be chosen to expose any errors in
    program
  • Different test sets used to expose different
    errors

67
Testing
  • Black Box. Consider programs function, not the
    actual code.
  • I/O partitioning
  • Data divided into classes
  • Data in same class cause qualitatively same
    behavior
  • Data in different classes cause different
    behavior
  • Test set should include at least one input from
    each class
  • Cause-effect graphing

68
Black Box Testing
  • Example find the roots of a quadratic function
    (ie where equation is 0)
  • Solution

69
  • public class QuadraticRoots
  • / The quadratic is ax2 bx c. a must be
    nonzero.
  • _at_exception IllegalArgumentException
  • thrown when coefficient of x2 is zero /
  • public static void outputRoots(double a,
    double b, double c)
  • if (a 0)
  • throw new IllegalArgumentException
  • ("Coefficient of x2 must be
    nonzero")
  • double d b b - 4 a c

70
  • if (d gt 0) // two real roots
  • double sqrtd Math.sqrt(d)
  • System.out.println
  • ("There are two real roots "
  • (-b sqrtd) / (2 a) " and
    "
  • (-b - sqrtd) / (2 a))
  • else if (d 0)
  • // both roots are the same
  • System.out.println
  • ("There is only one distinct root "
    -b / (2 a))
  • else // complex conjugate roots
  • System.out.println("The roots
    are complex")
  • System.out.println("The real
    part is " -b / (2 a))
  • System.out.println("The
    imaginary part is "
  • Math.sqrt(-d) / (2 a))

71
Black Box Testing
  • Three different qualitative behaviors
  • The roots are complex
  • The roots are real and distinct
  • The roots are real and the same
  • So partition the input into three classes.
  • Design test data so that each of the three
    classes are represented.

72
White Box Testing
  • Create test set based on an examination of the
    code.
  • Different levels of testing coverage.
  • Statement coverage. Weakest condition The test
    set results in each program statement being
    executed at least once.

73
White Box Testing
  • Statement coverage.
  • Example quadratic roots program
  • Test set (0,1,2), (1, -5,6),(1,-8,16),(1,2,5)
    causes all statements to be executed.
  • Test set (0,1,2),(1,-5,6),(1,3,2),(2,5,2) does
    not provide statement coverage.

74
White Box Testing
  • decision coverage. Test set causes each
    conditional in the program to take on both true
    and false values.
  • Example roots program

75
White Box Testing
  • outputRoots program. Three conditionals
  • a 0
  • d gt 0
  • d 0
  • for decision coverage require at least one set of
    test data
  • for which a 0 is true
  • and one for which it is false.
  • for which d gt 0 is true
  • and one for which it is false
  • for which d 0 is true
  • and one for which it is false.

76
White Box Testing
  • Example max program.
  • Test set (a,-1), (a,4) with a04
    2,4,6,8,9 provides statement coverage, not
    decision coverage.
  • Why?
  • apositionOfCurrentMax.compareTo(ai) lt 0
    never
  • becomes false
  • When a04 4,2,6,8,9 get both decision and
  • statement coverage.

77
/ generic method to find maximum object in
a0n _at_throws IllegalArgumentException
when n lt 0 _at_return position of max element
in a0n / public static int max(Comparable
a, int n) if (n lt 0) throw
new IllegalArgumentException
("MyMath.max Cannot find max of zero elements
") int positionOfCurrentMax 0
for (int i 1 i lt n i) if
(apositionOfCurrentMax.compareTo(ai) lt 0)
positionOfCurrentMax i return
positionOfCurrentMax
78
White Box Testing
  • Clause coverage. Each clause of each conditional
    must take both true and false values.
  • Clause a Boolean expression that contains no
    boolean connector (eg, , ).

79
White Box Testing
  • Example
  • if ((C1 C2) (C3 C4) S1
  • else S2
  • Decision coverage use one test set that causes
    ((C1 C2) (C3 C4) to be true, one that
    causes it to be false
  • Clause coverage
  • Must use a test set that causes each of the Ci to
    evaluate to true and each to evaluate to false.

80
White Box Testing
  • Clause coverage (Strong)
  • Must use a test set that causes each combination
    of clause values to be used
  • In example requires 16 sets of test data
  • Note that some combinations may not be possible.

81
White Box Testing
  • Execution Path Coverage.
  • Execution path a sequence of statements of a
    program in order of their execution.
  • Example outputRoots has only 4 execution paths.
  • Lines 1 - 3
  • Lines 1, 4 - 10
  • Lines 1, 4, 5, 11 - 14
  • Lines 1, 4, 5, 11, 15 - 20
  • Example max has varying number of execution
    paths
  • Depends on n.
  • When n lt 0, one execution path 1, 2, 3
  • When n 0, one path 1, 4, 5, 8
  • When n 1, 2 paths
  • 1, 4, 5, 6, 5, 8
  • 1, 4, 5, 6, 7, 5, 8
  • When n 3, 4 paths
  • for n, n gt0 there are 2n paths.

82
White Box Testing
  • Execution Path Coverage.
  • Requires test set that causes all execution paths
    to be executed.
  • For outputRoots program statement coverage,
    decision coverage, clause coverage, and execution
    path coverage are equivalent requirements.
  • For max program statement coverage, decision
    coverage, execution path coverage are different
  • Decision and clause coverage are same.

83
White Box Testing
  • Execution Path Coverage. Most demanding.
  • Test set that results in total execution path
    coverage also results in statement and decision
    coverage.
  • My not result in clause coverage.
  • Often requires an prohibitively large number of
    test data.
  • Not practical.
  • Minimum requirement for this class
  • Statement coverage
  • Must also test for special cases (ie boundary
    cases).

84
Sorting
  • Rearrange a0, a1, , an-1 into ascending
    order. When done, a0 lt a1 lt lt an-1
  • 8, 6, 9, 4, 3 gt 3, 4, 6, 8, 9

85
Sort Methods
  • Insertion Sort
  • Bubble Sort
  • Selection Sort
  • Count Sort
  • Shaker Sort
  • Shell Sort
  • Heap Sort
  • Merge Sort
  • Quick Sort

86
Insert An Element
  • Given a sorted list/sequence, insert a new
    element
  • Given 3, 6, 9, 14
  • Insert 5
  • Result 3, 5, 6, 9, 14

87
Insert an Element
  • 3, 6, 9, 14 insert 5
  • Compare new element (5) and last one (14)
  • Shift 14 right to get 3, 6, 9, , 14
  • Shift 9 right to get 3, 6, , 9, 14
  • Shift 6 right to get 3, , 6, 9, 14
  • Insert 5 to get 3, 5, 6, 9, 14

88
Insert An Element
  • // insert t into a0i-1
  • int j
  • for (j i - 1 j gt 0 t lt aj j--)
  • aj 1 aj
  • aj 1 t

89
Insertion Sort
  • Start with a sequence of size 1
  • Repeatedly insert remaining elements

90
Insertion Sort
  • Sort 7, 3, 5, 6, 1
  • Start with 7 and insert 3 gt 3, 7
  • Insert 5 gt 3, 5, 7
  • Insert 6 gt 3, 5, 6, 7
  • Insert 1 gt 1, 3, 5, 6, 7

91
Insertion Sort
  • for (int i 1 i lt a.length i)
  • // insert ai into a0i-1
  • // code to insert comes here

92
Insertion Sort
  • for (int i 1 i lt a.length i)
  • // insert ai into a0i-1
  • int t ai
  • int j
  • for (j i - 1 j gt 0 t lt aj j--)
  • aj 1 aj
  • aj 1 t
Write a Comment
User Comments (0)
About PowerShow.com