data structures dr. cong-cong xing dept of mathematics and computer science
TRANSCRIPT
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
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
• 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; }
• 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
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 []
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; }
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
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
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}
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
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?
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”
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
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.
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
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
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
• 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
• 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
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; } } }
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….. …… } }
subclassing, inheritance
idea:
superclass
subclass
subclass is not “sub”.
It actually has everything the superclass has, and probably more items.
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.
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(…)
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
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