Data Structures, Algorithms, & Applications

1 / 92

Data Structures, Algorithms, & Applications - PowerPoint PPT Presentation

Data Structures, Algorithms, &amp; Applications. John Barr. 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.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

PowerPoint Slideshow about 'Data Structures, Algorithms, & Applications' - jafari

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Data Structures, Algorithms, & Applications

John Barr

• 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.

The study of data structures and algorithms is fundamental to Computer Science.

• Algorithm design methods needed to develop programs that do the data manipulation.
Prerequisites
• Java
• Asymptotic Complexity
• Big Oh, Theta, and Omega notations
• My office data.
Web Site
• www.ithaca.edu/~barr/Student/CS311

Do Problem Set 1 by next week.

Assignments
• Submission procedures
• Assignment guidelines
Source Codes
• 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.
• 25% for problem sets/programs (~10)
• 40% for tests (3 tests; see web)
• 30% for projects
• 5% participation
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
Java

Topics:

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

Exception Classes:

• EmptyQueueException
• MyInputException
• UndefinedMethodException
MyInputException

Thrown by methods of class MyInputStream, defined in the book.

Java’s 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.

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. */

MyInputException

package exceptions;

public class MyInputException

extends RuntimeException

{

public MyInputException()

{super();}

public MyInputException(String message)

{super(message);}

}

MyInputStream

Catch exceptions of type IOException thrown by Java’s input methods

Throws exceptions of type MyInputException

Generic Methods
• Uses an interface class
• Is not an interface itself
• Can accept sub-classes that implement an interface class.
Generic Methods
• Not possible for Java primitive types.
• Use with subclasses of type Object
• Must write wrapper classes for primitive types.
Generic Methods

/** Swap the integers a[i] and a[j]. */

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 = a[i];

a[i] = a[j];

a[j] = temp;

}

Generic Methods

/** Generic method to swap the object

* references a[i] and a[j]. */

public static void swap(Object [] a, int i, int j)

{

Object temp = a[i];

a[i] = a[j];

a[j] = temp;

}

Generic Methods

package misc;

public class Abc

{

public static int abc(int a, int b, int c)

{return a+b+b*c+(a+b-c)/(a+b)+4;}

public static void main(String [] args)

{System.out.println(abc(2,3,4));}

}

Generic Methods

package misc;

public class Abc

{

public static float abc(float a, float b, float c)

{return a+b+b*c+(a+b-c)/(a+b)+4;}

public static void main(String [] args)

{System.out.println(abc(2,3,4));}

}

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.
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)
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.
The Computable Interface

package utilities;

/** Interface to be implemented by all classes

* that permit the standard arithmetic operations. */

public interface Computable

{

/** @return this + x */

/** @return this - x */

public Object subtract(Object x);

/** @return this * x */

public Object multiply(Object x);

The Computable Interface (cont)

/** @return quotient of this / x */

public Object divide(Object x);

/** @return remainder of this / x */

public Object mod(Object x);

/** @return this incremented by x */

public Object increment(Object x);

/** @return this decremented by x */

public Object decrement(Object x);

/** @return the additive zero element */

public Object zero();

/** @return the multiplicative identity element */

public Object identity();

}

Generic Method abc

package misc;

import wrappers.*;

import utilities.*;

public class GenericAbc

{

public static Computable abc(Computable a, Computable b, Computable 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));

}

}

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

{

/** @return -1 if this < x,

* 0 if this == x,

* 1 if this > x */

public int compareTo(Object x);

/** @return true iff this < x */

public boolean lessThan(Object x);

/** @return true iff this <= x */

public boolean lessThanOrEqual(Object x);

The MyComparable Interface

/** @return true iff this > x */

public boolean greaterThan(Object x);

/** @return true iff this >= x */

public boolean greaterThanOrEqual(Object x);

/** @return true iff this == x */

public boolean equals(Object x);

}

The Operable Interface

/** Marker interface for classes that are

* both Computable and Comparable. */

package utilities;

public interface Operable extends Computable, Comparable

{}

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();

}

The CloneableObject Interface

Cloning vs copying:

X = new currancy(3.42);

Y = x;

y.setValue(6.25);

System.out.println(x);

>> \$6.25

Why?

The CloneableObject Interface

X = new currancy(3.42);

x

3.42

The CloneableObject Interface

X = new currancy(3.42);

x

y

Y = x;

3.42

The CloneableObject Interface

X = new currancy(3.42);

x

y

Y = x;

y.setValue(6.25);

3.42

6.25

The CloneableObject Interface

X = new currancy(3.42);

Y = x.clone();

y.setValue(6.25);

System.out.println(x);

x

x

y

x

y

3.42

3.42

3.42

3.42

6.25

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();}

Wrapper Classes
• Built-in in Java
• Redefined in book to use book’s interfaces.
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;

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);}

Integer Wrapper Class(partial)

/** input from the given input stream */

public static MyInteger input(MyInputStream stream)

{

System.out.println("Enter an integer value");

}

/** make a clone */

public Object clone()

{return new MyInteger(value);}

Integer Wrapper Class

// Computable interface methods

/** @return this + x */

{

return new MyInteger

(value + ((MyInteger) x).value);

}

Integer Wrapper Class

// Comparable interface method

/** @return -1 if this < x,

* 0 if this == x,

* 1 if this > x */

public int compareTo(Object x)

{

int y = ((MyInteger) x).value;

if (value < y) return -1;

if (value == y) return 0;

return 1;

}

Integer Wrapper Class

// override Object.equals

/** @return true iff this == x */

public boolean equals(Object x)

{return value == ((MyInteger) x).value;}

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.

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;

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)
Methods as paramters

package misc;

import java.lang.reflect.*;

import wrappers.*;

import utilities.*;

public class Array1D

{

// instance data member

Object [ ] a;

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.

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.

/** 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");

a = new Object [n];

// input the elements

Object [] inputMethodArgs = {stream};

for (int i = 0; i < n; i++)

{

System.out.println("Enter element " + (i+1));

a[i] = inputMethod.invoke(null, inputMethodArgs);

}

}

catch (Exception e)

{

System.out.println(e);

throw new IllegalArgumentException("Array1D.inputArray");

}

}

Recursion
• Recursive (mathematical) functions
• Induction
• Recursive methods
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
Recursive functions
• f(5) = 5f(4) =20f(3) = 60f(2) = 120f(1)
Recursive functionsFibonacci numbers
• f(4)

= f(3)+f(2) =f(2)+f(1)+f(1)

= f(1)+f(0)+f(1)+f(1) = 3

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, m+1)
Induction
• Induction base: show true for n=0.
• Induction hypothesis: assume that claim is true for m, 0 <= m < n
• Induction step: prove for m+1
• Do it!
Recursive Methods

/** @return n! */

public static int factorial(int n)

{

if (n <= 1)

return 1;

else

return n * factorial(n - 1);

}

{// Driver for true recursive method rsum.

count++; // for if-else statement

if (a.length > 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) a[0].zero();

}

else

{

count++; // for conditional, rSum invocation,

return (Computable) rSum(a, n - 1).add(a[n-1]);

}

}

public class Permutation

{

/** perm(x, 0, n) outputs all permutations of x[0:n] */

public static void perm(Object [] list, int k, int m)

{// Generate all permutations of list[k:m].

int i;

if (k == m)

{// list[k:m] has one permutation, output it

for (i = 0; i <= m; i++)

System.out.print(list[i]);

System.out.println();

}

else

// list[k:m] has more than one permutation

// generate these recursively

for (i = k; i <= m; i++)

{

MyMath.swap(list, k, i);

perm(list, k+1, m);

MyMath.swap(list, k, i);

}

}

Permutations

a

b

c

c

c

b

a

a

b

b

a

c

a

b

c

c

b

a

b

a

c

c

a

b

b

b

c

a

a

c

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.

Testing
• Test set must be chosen to expose any errors in program
• Different test sets used to expose different errors
Testing
• Black Box. Consider program’s 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
Black Box Testing
• Example: find the roots of a quadratic function (ie where equation is 0):
• Solution:

{

/** The quadratic is ax^2 + bx + c. a must be nonzero.

* @exception IllegalArgumentException

* thrown when coefficient of x^2 is zero */

public static void outputRoots(double a, double b, double c)

{

if (a == 0)

throw new IllegalArgumentException

("Coefficient of x^2 must be nonzero");

double d = b * b - 4 * a * c;

if (d > 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));

}

}

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.
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.
White Box Testing
• Statement coverage.
• 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.
White Box Testing
• decision coverage. Test set causes each conditional in the program to take on both true and false values.
• Example: roots program
White Box Testing
• outputRoots program. Three conditionals:
• a == 0
• d > 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 > 0 is true
• and one for which it is false
• for which d == 0 is true
• and one for which it is false.
White Box Testing
• Example: max program.
• Test set {(a,-1), (a,4)} with a[0:4] = [2,4,6,8,9] provides statement coverage, not decision coverage.
• Why?
• a[positionOfCurrentMax].compareTo(a[i[]) < 0 never
• becomes false
• When a[0:4] =[4,2,6,8,9] get both decision and
• statement coverage.

/** generic method to find maximum object in a[0:n]

* @throws IllegalArgumentException when n < 0

* @return position of max element in a[0:n] */

public static int max(Comparable [] a, int n)

{

if (n < 0)

throw new IllegalArgumentException

("MyMath.max: Cannot find max of zero elements ");

int positionOfCurrentMax = 0;

for (int i = 1; i <= n; i++)

if (a[positionOfCurrentMax].compareTo(a[i]) < 0)

positionOfCurrentMax = i;

return positionOfCurrentMax;

}

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, &&, ||).
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.
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.
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 < 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 >=0 there are 2^n paths.
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.
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).
Sorting
• Rearrange a[0], a[1], …, a[n-1] into ascending order. When done, a[0] <= a[1] <= … <= a[n-1]
• 8, 6, 9, 4, 3 => 3, 4, 6, 8, 9
Sort Methods
• Insertion Sort
• Bubble Sort
• Selection Sort
• Count Sort
• Shaker Sort
• Shell Sort
• Heap Sort
• Merge Sort
• Quick Sort
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
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
Insert An Element

// insert t into a[0:i-1]

int j;

for (j = i - 1; j >= 0 && t < a[j]; j--)

a[j + 1] = a[j];

a[j + 1] = t;

Insertion Sort
• Repeatedly insert remaining elements
Insertion Sort
• Sort 7, 3, 5, 6, 1
• Insert 5 => 3, 5, 7
• Insert 6 => 3, 5, 6, 7
• Insert 1 => 1, 3, 5, 6, 7
Insertion Sort

for (int i = 1; i < a.length; i++)

{// insert a[i] into a[0:i-1]

// code to insert comes here

}

Insertion Sort

for (int i = 1; i < a.length; i++)

{// insert a[i] into a[0:i-1]

int t = a[i];

int j;

for (j = i - 1; j >= 0 && t < a[j]; j--)

a[j + 1] = a[j];

a[j + 1] = t;

}