Docsity

Managing Complexity - Lecture Slides | CS 261, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Managing Complexity - Lecture Slides | CS 261 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CS 261 – Data Structures

Managing Complexity

Why Study Data Structures?

Organize Information into Meaningful & Useful Units

Complexity Management

  • How do we manage complex problems?

Abstraction: Purposeful suppression of detail to aid in

understanding other aspects – create our own higher level model

To create an abstraction, we employ information hiding,

thus avoiding the need to understand details

We also often use some form of layering to apply

structure to our model

Abstraction

Example: Automotive Power Train

High level description or model

Hidden Details: Pistons, Valves, Spark plugs, Distributor, Carburetor, Fuel/air mixture, Combustion, Gear ratios, etc.

Reduced Transmission Rotation

Engine Rotation

Fuel Input

Layering: Division Into Parts

  • Divide a complex system into a manageable collection of

easier-to-understand components

  • Each component employs encapsulation to hide its

operational details – “HOW” it works

  • Components interact with each other through a fixed

interface that describes “WHAT” it does

  • In designing software:
    • “WHAT” specifies the interface.
    • “HOW” defines the implementation.
  • Encapsulation & Interchangeability: can create many different implementations for a given interface

Layering: Division Into Parts

Example: Computer system

Components: CPU

Storage (memory, disks, CD-ROM, etc) I/O (keyboard, mouse, monitor, printer)

  • How many of you know everything there is to know about how a computer works?
  • Who can tell me all the details of the graphics board on their computer?
  • Yet all of you (should be able to) use and even program computers
  • Some of you can even fix computers (without even knowing everything about how they work)

Division into Parts: Service View

  • Service View describes high level components in terms of

their interfaces – i.e., WHAT they do

Example: Buying flowers for a friend

  • Patterns: Identify tools/ideas/services from previously solved problems that can be used to solve a new problem
  • Abstract Data Types (ADTs): Interface specifications for commonly used services performed on data

Me Florist Delivery Person Friend

Wholesaler

Flower Arranger

Grower Gardener

Division into Parts: Repetition

  • Complex system comprised of a collection of similar

components

  • Divide understanding between single component and

structure of entire collection

  • Repetition of …
    • Components: Cylinders in an engine, Neurons in the brain, Arrays, Matrices, Trees, Graphs
    • Execution or behavior: Mathematical induction, Recursion, Iteration (loops)

Repetition: Recursion

  • Recursion: define large, repetitive problem/system in terms of smaller instance(s) of same problem/system (plus base case(s) )

Example: Self-similarity in nature, fractals

  • Trees can be thought of as a trunk with smaller versions of a similar tree attached ( base case  a leaf )

Example: Fibonacci numbers

Fn – the n th^ Fibonacci number – is defined as Fn = Fn -2 + Fn - for n > 2 and F 1 = F 2 = 1. int fibonacci(int n) { if (n <= 2) return 1; return fibonacci(n–2) + fibonacci(n–1); }

Base cases

Recursion

  • A method/function that invokes itself is recursive
  • Must include a conditional that divides execution into two

(or more) cases:

  • Base case(s): does not contain a recursive call
  • Recursive case(s): calls itself with a smaller problem
  • Base case we can understand
  • Recursive call creates new instances of parameters and

local variables:

  • Activation record

Recursion: Towers of Hanoi

  • Move the disks from pole A to pole B:
    • Can only move one disk at a time  only the topmost disk of any pole.
    • Can NOT place a larger disk on a smaller disk.
  • Solution: Treat the top n – 1 disks as a unit (use recursion)

A B C

Recursion: Towers of Hanoi

  • Move top n - 1 disks from pole A to pole C (using B ):

public void solveHanoi(int n, byte a, byte b, byte c) { // Move top n disks from pole a to pole b using pole c. if (n == 1) moveDisk(a, b); // Base case: move one disk. else { // Recursive case: solveHanoi(n-1, a, c, b); // Move top n -1 disks from a to c using b. moveDisk(a, b); // Move bottom disk from a to b. solveHanoi(n-1, c, b, a); // Move top n -1 disks from c to b using a. } } A^ B^ C

Any Questions?

CS 261 – Data Structures

Algorithms

Algorithms

  • Describe the steps for solving a problem
    • Recipe for a solution
  • Not tied to any language
  • Examples:
    • Quick sort
  • In Java, use methods/functions to implement algorithms
    • Jump between algorithmic description and Java implementation

Algorithm Characteristics

  • Accurate specification of input
    • and type of inputs, pre-conditions

  • Results, side effects
    • Post-conditions, output, global variables (not a concern in Java)
  • Precise specification of instructions
    • Avoid ambiguity
  • Termination, execution time (Chap. 4)
    • Stops after finite # of steps, asymptotic complexity
  • Correctness (Chap. 5 – Need to read it on your own)
    • Achieves the desired result, free from errors

Specification of Input: Pre-conditions

  • Pre-conditions specify constraints on the range of valid

parameter values:

public char digitChar(int val) { // Pre : val must be between 0 and 9. // Post: return val’s character equivalent. switch(val) { case 0: return ‘0’; case. 1: return ‘1’; .. case 9: return ‘9’; } }

  • What happens if the pre-conditions are not followed:

Example: val = -

Specification of Input: Validity Checking

  • Ultimately, the code itself should check input validity:

public char digitChar(int val) { // Pre : val must be between 0 and 9. // Post: return val’s character equivalent. if (val < 0 || val > 9) throw new Exception(“digitChar: argument ” “out of range”); return (char)(‘0’ + val); // Return char for val. }

  • An Exception allows for a reasonable error message and provides the opportunity to remedy the problem with a “ catch ”
  • Validity of input can not always be checked by code:
    • E.g., numeric overflow

Description of Results/Output

  • Function/method name should indicate purpose:
    • Combined with parameter names and types (e.g., min – of what?)
    • Return type indicates the form that the result will take
  • Describe outputs similarly to inputs:
    • Comment on function’s purpose
    • Post-conditions
  • Document side effects:
    • Print, draw, or other output statements
    • Modification of class or parameter variables
    • A method with a void return type must have some side effect
    • Global variables (not a concern in Java)

Instruction Precision

  • Computers are not intelligent:
    • Performs a limited number of simple instructions (but very quickly)
    • Perform exactly what instructed (assuming no hardware bugs)
  • Algorithmic clarity:
    • Each step must be precisely defined – avoid ambiguity
    • Informal and natural language descriptions (e.g., English) can be ambiguous/ill-defined
    • Example: instructions in a recipe
      • “Beat egg yokes and sugar until thick and light”
      • “Beat egg whites until stiff but not dry”

Termination: Example – power

  • Compute the integer power of a double:

*public double power(double base, int n){ double result = 1.0; for(int i = 1; i <= n; i++) result = base; return result; }

  • In some cases, simple loops can be rewritten to use the

desired property directly:

*public double power(double base, int n){ double result = 1.0; while (n-- > 0) result = base; return result; }

Can we use i as the property? How about n?

Termination: Example – gcd

  • Compute the greatest common divisor of two integers:

public int gcd(int n, int m) { // Pre: assume n and m are greater than or equal to zero. // Post: return the greatest common divisor of n and m. while (m != n){ if (n > m) n -= m; else m -= n; } return n; }

Can we use m as the property? How about n? Any other ideas?

Space Utilization

  • Some algorithms use more space/memory than others :
    • Example: some sort algorithms copy the data while others don’t
  • Tradeoff between space utilization and execution time:
    • Known as the time/space tradeoff
    • When working with large datasets, sometimes need to compromise execution time to keep memory usage down

Any Questions?