Data Structures Dr. Cong-Cong Xing Dept of Mathematics and Computer Science.

136
Data Structures Dr. Cong-Cong Xing Dept of Mathematics and Computer Science

Transcript of Data Structures Dr. Cong-Cong Xing Dept of Mathematics and Computer Science.

Data Structures

Dr. Cong-Cong Xing

Dept of Mathematics and Computer Science

Review of Java Basics

The Java Environment

Java source file

Java compiler

Byte code file

JVM for your platform

Byte code can be disseminated to other machines. It is the “machine code” for JVM

JVM = Java Virtual Machine (a software “computer”)

The Basic Program Structure

public class MyProg{ …… // static variables

public static void main (String[] args) { … … // computations, calls } ….. public static …. // method 1 public static …. // method 2 }

Execution starts here

The “hello, world” (again)

public class Lab1{ public static void main(String args[]) { // printout the message System.out.println(“Hello, World!");

// terminate the program System.exit(0);

} // end of main} // end of class Lab1

Execution under Dr. Java

Input/output using JOptionPaneimport javax.swing.JOptionPane;

Primitive Data Types

Type meaning Value example

int integer 1, 9, -2, 0, 3

double real 34.2, 33.1, -0.233

char character ‘a’ , ‘b’, ‘(‘

boolean logic true, false

Operators

Operator Meaning

! Negation

*, /, % Multiplication, division, modulo

+, - addition, subtraction

<, <=, >, >= relational operation

==, != equal, not equal

&& logical and

|| logical or

high

Java Control Statements

Sequence and compound statements

{ ….. stmnt1; stmnt2; stmnt3; …}

{ and } marks the begin and end

; is used to separate individual stament

Selection • if … else… statement

if (x > 1) { x = x+10;}else{ x = x-10;}

• switch (case) statement

switch (num) { case 1: System.out.println(“It’s 1”); break; case 2: System.out.println(“It’s 2”); break; case 3: case 4: case 5: System.out.println(“It’s 3 or 4 or 5”); break; default: System.out.println(“Invalid data”); break; }

Loops• while-loop

while (counter <= 5) { System.out.print(counter); counter = counter + 1; }

• for-loop

for (i=1; i<=10; i++) { System.out.println(“this is”+i+”pass”); System.out.println(“i is “+i); }

Methods

Ideas involved• functions, procedures, operations,

subprograms, modular programming, abstract data types (ADT)

• static (class) methods: the rest ideas• non-static (object) methods: the idea of ADT

static methods

public static int sq (int x) { return x*x; }

….

return valtype name of

method

parametername

what isreturned parameter

type

To call/invoke a method

Just like you call a math function:

Method-name (argument)

Ex: sq(1); a = sq (1); System.out.print(sq(1));

Structure of class w/ static methods

public class class-name { public static … method1(…) { … } public static …. method2(…) { …. } ………………. pubic static void main(String args[]) { ….. } }

call

call

The class Math

Built-in class Includes all commonly used math

functions:• Math.sin• Math.cos• Math.log (natural log)• Math.sqrt • Math.PI ….. (see p 615 for more)

Arrays

1-D array

int[] a = new int[10];

declare variable a to be of type int array

create an int array of 10 cells in memory

let this array (crated by the right) be referenced/represented by variable a

graphically,

int[] a = new int[10];

a

a[0] a[1] a[2] a[8] a[9]

2-D arrays• similar to 1-D array • actually, 1-D array of 1-D arrays

int[][] matrix = new int[3][4];

// a 3x4 (3 rows, 4 columns) int array referenced by variable matrix

graphically,

int[][] a = new int[3][4];

a[0][0] a[0[1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

a[0]

a[1]

a[2]

a[0][0] a[0][1] a[0][2] a[0][3]

a

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

int [][]

int []

int []

int []

int [] : 1-D array, elements are of type intint [][] : 1-D array, elements are of type int []

Review of Structure Chart

Overview

Design of program: structure chart (style) How to read the chart?

• from top to bottom; from left to right,

START

Declare r, area, rs

double r,areaString rs

Prompt and read r

rs=JOptionPane.showInputDialog(“enter a radius”);

r=Double.parseDouble(rs);

Echor

System.out.println(“radius is”+r);

Computes area

area=pi*r*r

Display area

System.out.println(“area is “+area);

if statement

if ( grade >= 60 )

{ System.out.println(“you passed”);

System.out.println(“good work”); }

Its structure chart:grade>=60

print “you passed”

T

print “goodwork”

if-else statement

Its structure chart

grade>=60

print “youpassed”

print “congratulations”

print “work harder”

print “youfailed”

T F

if (grade >=60) { System.out.println(“you passed”); System.out.println(“congratulations!”); } else { System.out.println(“you failed”); System.out.println(“work harder!”); }

Cont’d

X=0?

X>0?zero

pos neg

T F

T F

if (x==0){ System.out.println(“zero”);}else{ if (x>0) { System.out.println(“positive”); } else { System.out.println(“negative”); }}

Cont’d

if (x==0) System.out.println(“zero”);if (x>0) System.out.println(“positive”);if (x<0) System.out.println(“negative”);

X>0?X=0? X<0?

zero pos neg

T T T

Switch statement

switch (expression) { case label1: stmnt1; break; case label2: stmnt2; break; …… case labeln: stmntn; break; default: default stmnt; break; }

Cont’d

Structure chart

Switch()

stmnt1 stmnt2 stmnt3 stmntn

exp=l1 exp=l2 exp=l3exp=ln

while-loop

while (cond)

{ stmnt1;

…..

stmntn;

}

stmnt1 stmnt2 stmntn

cond

example• Design: (note how the• loop is represented)

START

P & R first grade

grdstr

Convertgrdstr to grd

echo

sum=0n=0

accumulate total grade

add currentgrd to total

sum=sum+grd

increase #of students

n=n+1

P &Rgrdstr

convertgrdstrto grd

echo

computeavgerage

avg=sum/n

displayavg

end

whilegrd !=9999

for-loop

For i=1 to 10,i++

Print i

for (i=1;i<=10;i++) { System.out.println(i); }

Nested loop

for (i=1; i<=5; i++)

{

for (j=1; j<=6-i; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

Println()

Print”*”

For j=1;j<=6-i;j++

For i=1,i<=5,i++

Function calls (modular programming) Problem: Given a positive integer n, compute 1+2+…+n

Requirements: Users input a positive integer n, the program computes the sum from 1 to n. E.g.,

if n=1, output = 1 if n=2, output = 1+2=3 if n=10, output = 1+2+…+10=55

Specification: • Input: positive integer n• Output: 1+2+…+n• Relevant formula/methodology: modules, loops

For each method, make its own structure chart

• Method getN: • purpose: It takes nothing and returns the positive integer entered by the user• type: void int• data structure

getN()

sn=JOpt… convert sn to n return n

Name Type usage

n Int Input, positive integer

Sn String String for n

Cont’d

doComp(int n)

sum=0

sum=sum+i

return sumfor i=1 to n

Method doComp:* purpose: computes 1+…+n and returns the result.* type: int int* data structure

Name Type Usage

n int formal parameter

i int loop controller

sum int hold 1+…+n

Cont’d

display(int r)

print r

Method display:purpose: display the resulttype: int voiddata structure

Name Type Usage

r int formal parameter

Method main

Main(String args[])

result=doComp(num)

Num=getN()

display(result)

end

Code sketch (lab?)

import javax.swing.*;

public class Lab{// put method getN here// put method doComp here// put method dispaly here

// put method main here}

End of Review of Java basics

Chapter 5 Recursion

5.1 Introduction to Recursion

Idea of Recursive Thinking

Copy of itself

Recursive Thinking

What is recursion?• Solve a (large) problem by solving

subproblems that have the same nature as the original problem.

• In terms of programming, a function calls itself.

………f(n)….{ …f(n-1)….}

Recursion in math

• In term of functions, solve f(n) by solving typically f(n-1).

• Same idea as mathematical induction (Math 358).

• Well-known example: factorial • n!=n*(n-1)! Or• fac(n) = n*fac(n-1)

Ex: find the length of a string s• If s is empty, the len(s)=0• Otherwise, s=aw,

• where a is a character and w is shorter string. Then,

len(s) = 1+len(w)

a

w

Java code

Recursion stops

Recursive calls

Substring from index 1 to end. (string methods, p618)

String comparison method

String methods (p 618)

Trace of compLength(“ace”) (Study carefully)

• Trace of compLength(“ace”)

• Trace of compLength(“ace”)

• Trace of compLength(“ace”)

• Trace of compLength(“ace”)

0

1

1

2

1

2

=3

• Summary

• Run-time stack and Activation Records/Frames saved in memory

• Run-time stack and Activation Records/Frames

• Run-time stack and Activation Records/Frames

• Run-time stack and Activation Records/Frames

• Run-time stack and Activation Records/Frames, memory clear up at this time

Memory cleared up now

Trace by Activation Record (p 251)

BNF Grammar

Nackus-Naur Form (BNF) Standard method for specifying language

grammars Ex:

• A ::= e (empty string)

| (A)

What is the language specified by this BNF?

• Ex:

D ::= 0

| 1

| DD

What is the language defined by this BNF?

BNF and Induction

The idea represented by BNF is the same thing as (structural) induction we studied in math/theory.

Ex: we can define logical expressions

in the following inductive way

• True is a logical expression • False is a logical expression• If E1 and E2 are logical expressions, so is

AND(E1,E2)• If E1 and E2 are logical expressions, so is

OR(E1,E2)• If E is a logical expression, so is NOT(E)

Basis steps

Induction steps

Or, in the manner of BNF

bExpr ::= True | False

| AND(bExpr,bExpr)

| OR(bExpr,bExpr)

| NOT(bExpr)

Ex: AND(True, OR(True,False)) is a bExpr

Ex: string reversal (lab?)

• Basis : rev (“”) =“”• Inductive step: rev(aw) = rev(w) + “a”

• Rev(“abcdefg”) = rev(“bcdefg”) + “a”

= rev(“cdefg”)+”b”+”a”

= “gfedcba”

5.2 Recursions in Math

ex: factorial

up to n

can we see ‘a problem contains itself?’

• (basis) • (inductive step)

• Java code (method of computing factorial) (left as a lab)

Trace of f(4)

Ex: compute recursively

n times

can we see ‘a problem contains itself?’

Ex: compute

• Basis: n=0, • Inductive step:

• Java code fragment

GCD (greatest common divisor)

• Euclidean Algorithm gcd(m,n) = n if n is a factor of m

gcd(m,n) = gcd(n, m mod n) otherwise

Ex: gcd(7,5) = gcd(5,2) = gcd(2,1)=1

gcd(2,5) = gcd(5,2) = gcd(2,1) = 1 (note: m<n in this case)

gcd(25,12) = gcd(12,1)= 1

gcd(12, 9) = gcd(9,3) = 3

Java code fragment

5.2 Recursive Searching

Searching

Problem • Given an array A, and an element x, decide if

this x is in A. If yes, return the index of x, otherwise return -1.

• Ex:

A: | 3 | 4 | -4 | 21 | 98 | -2 | 23 |

x = 98, result =4; x =100, result = -1

Linear Search

Algorithm (idea)• Start searching by comparing x with the first

element (head) indexed by, say, i of the array to see if they are equal

• If yes, return i• If no, search again starting with element

indexed by (i+1)• Repeat until the array is exhausted.

Java code

Java code

Binary Search

Algorithm (idea)• Array is already sorted (from small to large)• Compare x with the middle element • If yes, return index• If no,

• If x < middle element, search the first half of the array;

• If x> middle element, search the second half of the arrray

example

Ex:

“new” last = middle -1

“new” first = middle +1

3 4 8 11 22 34 56 89 90 101 ------------------------------------------------------------------------ look for 8 0 1 2 3 4 5 6 7 8 9 f * l

3 4 8 11 22 34 56 89 90 101 ------------------------------------------------------------------------ 0 1 2 3 4 5 6 7 8 9 f * l

3 4 8 11 22 34 56 89 90 101 ------------------------------------------------------------------------ 0 1 2 3 4 5 6 7 8 9 f * l found, index 2 returned

Time Complexity of Programs

The big-O notation Ex:

• O(• O(• O(• O(• O(

Meaning:• Roughly speaking: O(f(n)) says the upper

bound of your program’s running time is f(n), where n is typically the size of input to the program (e.g., the length of an array)

• Ex:• If T(n) = O(, which means that time consumed by

your program is proportionally upper-bounded by That is, the worst-case situation of your program is roughly

Input n O(n) O(log n) O(n^2) O(2^n)

8 8 3 16 256

16 16 4 256 65536

32 32 5 1024 4294967296

64 64 6 4096 1.8x10^19

100 100 6< …<7 10000 1.3x10^30

1000 1000 About 10 10^6 huuuuuuuge

The “feel” of different big-O. Think of the number represented by big-O as seconds

This is already over millions of years

Ranking order (proof?)• O(• O(• O(• O(• O(• O(

Small

large

• How to determine big O?• A quicker, informal way is: (formal way is

beyond the scope of our this course)• Drop lower-degree terms, drop coefficients• Ex: if

then • ex: if

then

Can we formally prove

Pf: • Method 1: Induction on n (natural number)• Basis: trivial • Induction:

• Method 2: elementary math

• Compare k and 2^k.

k = 1+1 +……+1 (k times)

2^k = 2*2*….*2 (k times)

>2+2+….+2

>1+1+….+1

Question:• Where should be in the ranking list?• (Left as a hw problem)

Program Analysis

Count the number of major operations Ex:

• Sum =0;• for (i=1; i<n; i++)

sum = sum +1;

What is the time complexity of this code fragment?

Cont’d Ex: bubble sort. What is the time complexity?

for (i=0; i<=(n-2); i++) { for (j=i+1; j<=(n-1); j++) { if (a[i]>a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } }

Ch 1 Object-Oriented Programming

Basic Terminologies

OOP - object-oriented programming OOPL - object-oriented programming

languages Java & OOP

• Java is just one of the many existing OOPL• Java does not represent OOP paradigm.

ADT - Abstract Data Types• A set of data grouped/enclosed together w/

operations on the data• Access to data from outside can only be done

through “gate”• an object (later on) is an ADT

ADT, Objects

No other way to access (“see” it, or “change” it) except going through this “gate” (or some other gates)

Interface (or Java interface) – • type of methods. (how many parameters,

their types, return type)• Type of classes

• Specifies what kind of methods are in the classes• Ex: stack ADT/classes

• Push : int stack• Pop : () stack• Top: () int

Classes, objects

All the things in this section are intuitive but informal• A class is the manufacturer of objects.• An object is born (or made) from a class by

“newing”.

object = new some-class

New Program Structure

public class T{.. // data

// non-static methods }

public class T1{.. // data

// non-static methods }

public class Work{

public …main(String[] args) { obj1 = new T(…); obj2 = new T1(…);

// call methods through // obj1, obj2….. …… } }

example

examplecreate an object pc

call pc’s getRamSize method

subclassing, inheritance

idea:

superclass

subclass

subclass is not “sub”.

It actually has everything the superclass has, and probably more items.

Unified Modeling Language

Example (UML diagram)

Java way of saying subclassing

Issues w/ inheritance

method overriding• method f in superclass can be overridden in

subclass (based on the need)• when f is called through a subobject,

(message f sent to subobject), the new f, not the old f inherited from superclass, will be invoked.

Method f()….

Method f()…(redefined).

Superclass T

Subclass Sa = new Sa.f()

Subclassing/subtyping• Subclassing = inheritance• Subtyping: if T is a subtype of S (T<:S), and

x is of type T, then x is also of type S. Ex: int is a subtype of double, so 1 of type int can also be regarded as of type double. In code,

double a;

a = 1;

is acceptable (no type error).

• So, subclassing and subtyping are two different concepts.

• However, in Java, (although unsound in theory), subclassing and subtyping are treated as the same thing. This is, if A is a subclass of B, then any object of A can also be regarded as of B.

Ex:// pc is of type ComputerComputer pc;

// the following is ok, will not// cause type errorpc = new Notebook(…)

ex:

ok

Not ok, caught statically

Polymorphism (or dynamic dispatch)• A supertype variable can hold either a

superobject or an subobject (due to subtyping, as we have seen)

• If a method m is overridden in subclass, which method will be called in x.m(), the m in superclass or the m in subclass? (x is a supertype variable)

• Answer is: depending on what x is at run time. Thus, dynamic binding/dispatch.

getX() in ColorPoint, not in Point, is called

• Better ex:

Which getX() will be called?

Single Linked List

Concept• Different items are linked by “pointers”• “pointers” are called references in Java• Ex: (in general)

xh

1 2 3 4 5

• In Java, we need to a Node first

UML diagram notation

References and Pointers

• …Given that structures are gone, and arrays and strings are objects, the need for pointers to these constructs goes away. Thus, Java has no pointer data types… (http://java.sun.com/docs/white/langenv/Simple.doc2.html)