0% found this document useful (0 votes)
31 views

Chapter 1

The document introduces data structures and algorithms. It discusses the purpose of the course as introducing commonly used data structures and algorithms, as well as algorithm analysis. It provides examples of using different data structures to solve various problems like games, library management, and traffic light control.

Uploaded by

Jie Lin
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Chapter 1

The document introduces data structures and algorithms. It discusses the purpose of the course as introducing commonly used data structures and algorithms, as well as algorithm analysis. It provides examples of using different data structures to solve various problems like games, library management, and traffic light control.

Uploaded by

Jie Lin
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 88

Data Structure & Algorithm Analysis in Java

Mark Allen Weiss Chen Peipei July 7, 2005

Chapter 1
Introduction

The purpose and contents of the course


Introduce most used data structures and algorithms Prerequisite of other courses Introduce algorithm analysis Review Java and C++

The purpose and contents of the course


1. Introduce most used data structures and algorithms. Use proper data structures to solve different problems.
Example : Game problem Management of library catalogue by computer Management of the traffic lights in intersections The book : selection problem
solve a popular word puzzle

The purpose and contents of the course


Example 1:
Game problem:

Next step:
x has five choices.

The purpose and contents of the course


Example 1 uses a tree structure.

The purpose and contents of the course


Example 2: Management of library catalogue by
computer D.S. Sartaj Sahni 000001 computer 2000.1

It is a linear list.

The purpose and contents of the course


Example 3:
Management of the traffic lights in intersections
C B A D E C, E are one-way road, there are 13 path to go. Can go at the same time : AB EC

Cannot go at the same time:


This is a graph EB AD

The purpose and contents of the course


Example 4:
The book : selection problem :
a group of N numbers and wold like to determine the kth largest

solve a popular word puzzle:


1 1 t 2 h 3 i 4 s

2 w
3 4 o f

a
a g

t
h d

s
g t

The purpose and contents of the course


2 . Prerequisite of other courses: Principles of compiling : use stack to compute
expression and implement recursive procedure

Operating System: use queue to implement job


scheduling

Database: use B-tree,B+ tree to organize, store


and load massive data in the hard memory. ...

The purpose and contents of the course


3. Basic methods of algorithm analysis standards of the performance of an algorithm: time complexity, space complexity, and accuracy example: a1,a2,a3,,an-1,an

4. Review Java and C++

What is Data Structure


1. Data is the carrier of information. Data is a set of numbers , characters,and other symbols that can be used to describe the objective things. These symbols can be input into computers , identified and processed by the computer program.

What is Data Structure


Data can divided into two classes: numerical data: int, float, complex, non-numerical data: character, string, graph, voice

What is Data Structure


. Data structure A data structure is a data object together with the relationships among the data members that compose the object Data_Structure={D,R} is a data object R is a limited set of relationships of all the data members in D.

What is Data Structure


Linear structure
Data structure Non-linear structure

What is Data Structurem


----- -----

ADT and OO
1. Data type Definition: is a set of values together with a operation set that operate on these values. Example: int type value set: {,-2,-1,0,1,2,} operation set: {+, -, *, /, %, }

ADT and OO
Most of the programming languages provide a group of predefined data type. Atom data type int, float, double Structure data typearray, struct,

ADT and OO
2. ADTs: Abstract Data Types
Abstract: is a method used to hide the information.
Example: int x ; : x=735; : abstract of int data type assignment float x, y ; : x=x*y+3.0; : abstract of float data type operation

ADT and OO
Abstract data type: is a new programming method that part the usage and implementation, in order to encapsulate and hide the information.

ADT NaturalNunber is objects: , 0, (MAXINT) Function: Zero( ):NaturalNumber IsZero(x):Boolean Add(x,y):NaturalNumber Equal(x,y):Boolean Successor(x):NaturalNumber Subtract(x,y):NaturalNumber end NaturalNumber

ADT and OO
3. OO: object-orientedobjectclassinherit communicate object: attribute values+ operates class: objects of same attributes and operates. an instance is an object of the class. different object has deferent attribute value

ADT and OO
Inherit:
base classintegrate the same part (including attributes and operations) in all the derived classes derived classadd the specific attributes and operations Example: base classpolygon derived classquadrilateral,triangular

ADT and OO
Communication: each class object communicate with others using messages. Message: instructions that one class object used in order to require another class object to perform some operation.

Algorithm definition
Algorithm : an operation sequence of soluting a problem Characteristic: 1.finite 2. deterministic 3. initial action 4. sequence ends

Algorithm definition
Program : is written by languages that can be performed by machine. cant satisfy the finiteness. For example, OS. Algorithm: has multiple descriptive methods, such as language, graph, table.

Algorithm definition
void selectsort(int a[ ],int n) { for (int i = 0; i < n-1; i++) { int k = i; for ( int j = i+1; j < n; j++) if ( a[j] < a[k]) k = j; int temp = a[i]; a[i] = a[k]; a[k] = temp; } }

Mathematics Review
1. Exponents
XAXB = XA+B XA/XB = XA-B (XA)B = XAB XN + XN = 2XN 2N + 2N = 2N+1

Mathematics Review
2. Logarithms( all logarithms are to the base 2)
DEFINITION : XA = B if and only if logXB = A THEOREM 1.1 logAB = logCB/ logCA ; A, B, C > 0, A != 1 THEOREM 1.2 logAB = log A + log B; A, B > 0

3. Series N 2i = 1 + 21 + 22 ++2N = 2N+1-1


i=0 N

i = 1 + 2 + 3++N = (N+1)*N/2
i=1

Mathematics Review
4. Modular Arithmetic
We say that A is congruent to B modulo N, written A B ( mod N), if N divides A-B. Example : 81 61 1 (mod 10)

Mathematics Review
5. The P Word ()
1). Proof by Induction The first step is proving a base case. the Next stap an inductive hypothesis is assumed. theorem is assumed to be true for all cases up to some limit k. Using this assumption, the theorem is then shown to be true for the next value, which is typically k + 1. This proves the theorem( as long as k is finite). Example: see book P6

Mathematics Review
2). Proof by Contradiction Proof by contradiction proceeds by assuming that the theorem is false and showing that this assumption implies that some known property is false, and hence the original assumption was erroneous. Example: proof that there is an infinite number of primes

A Brief Introduction to Recursion


1. Recursive example: define a function f, valid on nonnegative integers 0 x=0 f(x) = 2f(x-1) + x2 x > 0 f(1) = 1, f(2) = 6, f(3) =21, f(4) = 58
public static int f ( int x) { if ( x = = 0) //base case return 0; else return 2*f(x-1) + x*x; //recursive call }

A Brief Introduction to Recursion


A nonterminating recursive method: public static int bad( int n ) { if ( n = = 0) return 0; else return bad( n/3 + 1) + n-1; } two fundamental rules of recursion: 1) Base cases. 2) Making progress.

A Brief Introduction to Recursion


2. 1) direct recursive

2) indirect recursive Example 1 factorial function f(n)=n! 1 n<=1 (base) f(n) n*f(n-1) n>1 (recursive component)
f(5)=5f(4)=5*4f( 3)=5*4*3f(2)=5*4*3*2f(1)=120
static long factorial (int n) { if ( n <= 1) return 1; else return n* factorial( n-1 ) }

A Brief Introduction to Recursion


public class ComputeFactorial { public static void main( String[ ] args ) { System.out. Println( please enter a nonnegative integer ); int n = MyInput.readInt( ); Syatem.out.println( Factorial of + n + is + factorial( n ) );

} static long factorial (int n) { if (n<=1) return 1; else return n*factorial(n-1); }


}

A Brief Introduction to Recursion


Example 2: Compute Fibonacci number
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, fib(0) = 0; fib(1) = 1; fib(n) = fib(n-2) + fib(n-1); n>=2 public static long fib(long n) { if ( ( n = = 0) || ( n = = 1 ) ) return n; else return fib(n-1) + fib(n-2); }

Compute fib(4):

A Brief Introduction to Recursion


public class ComputeFibonacci { public static void main( String args[ ]) { System.out.println( Enter an index for the Fibonacci number ); int n = MyInput.readInt( ); System.out.println( Fibonacci number at index + n + is + fib(n)); } public static long fib(long n) { if (( n = = 0) || ( n = = 1)) return 1; else return fib( n-1) + fib(n-2); } }

A Brief Introduction to Recursion


Example 3: computes the sum of the elements a[0] through a[n-1] a[0], a[1], , a[n-2], a[n-1]

A Brief Introduction to Recursion


public static int Rsum(int[] a , int n) { if (n>0) return Rsum(a,n-1)+a[n-1]; return 0; } a0 a1 a2 a3
Rs(a,4)----->Rs(a,3)+a[3] Rs(a,2)+a[2] Rs(a,1)+a[1] Rs(a,0)+a[0]

A Brief Introduction to Recursion


Example 4: Permutation {a,b,c} : abc, acb, bac, bca, cab, cba permutation of n elements has n!

A Brief Introduction to Recursion


public static void perm(Char[ ] list , int k, int m) { int i; if (k= =m) { for (i=0; i<=m; i++) cout << list[i]; cout << endl; } else{ for (i=k; i<=m; i++) { swap(list[k], list[i]); perm(list, k+1, m); swap(list[k], list[i]); } }

A Brief Introduction to Recursion


Example 5 : Hanoi tower problem

public void moveDISKs(int n, char fromTower, char toTower, char auxTower) if ( n= =1) Move disk 1 from the fromTower to the toTower; else { moveDISKs(n-1, fromTower, auxTower, toTower); Move disk n from the fromTower to the toTower; moveDISKs(n-1, auxTower, toTower, fromTower); }

A Brief Introduction to Recursion


public class TowersOfHanoi { public static void main(String[ ] args) { System.out.printLn( Enter number of disks ); int n = MyInput.readInt( ); System.out.printLn( The move are:); moveDISKs(n, A, B, C); } public static void moveDISKs(int n, char fromTower, char toTower, char auxTower) { if ( n= =1) System.out.printLn( move disk + n + from + fromTower + to + toTower); else { moveDISKs(n-1, fromTower, auxTower, toTower); System.out.printLn( Move disk + n + from + fromTower + to + toTower ); moveDISKs(n-1, auxTower, toTower, fromTower); } }}

Generic Objects in Java


Throughout this text, we will describe algorithms and data structures that are type independent. IntCell nongeneric class MomoryCell generic class

Generic Objects in Java


1. IntCell class public class IntCell { public IntCell ( ){ this ( 0 ); } public IntCell( int initialValue ) { stoedValue = initialValue ; } public int read ( ) { return storedValue; } public void write ( int x ) { storedValue = x; } private int storedValue; }

Generic Objects in Java


1) public and private memble of public : may be accessed by any method in any class . member of private : may only be accessed by methods in its class. specifier is omitted (package-friendly visibility) : a data member whose visibility specifier is omitted is visible to other classes in the same package.

Generic Objects in Java


2) constructor
A class may define methods that describe how an instance of the class is constructed; these are called constructors. If no constructor is explicitly defined, one that initializes the fields using language defaults is automatically generated.

Generic Objects in Java


3) This
In many cases,the zero-parameter constructor can be implemented by calling anather constructor. By using this , we avoid replicating code logic in separate constructors. A different use of this is as a reference to the object being acted upon.

Generic Objects in Java


public class TestIntCell { public static void main ( String [ ] args ) { IntCell m = new IntCell ( ); m. write( 5 ); System.out.println( Cell contents: + m.read( ) ); } }

Generic Objects in Java


1) static and main The main method must be static , meanimg that it applies to the TestIntCell class instead of a single instance of the class. Each class may declare a main method that will be used when the java interpreter is called for that class. 2) Object creation. Objects are created by using new.

Generic Objects in Java


3) Method calls. m.write(5); m.read( ) m.storedValue //be illegal

Generic Objects in Java


2. MemoryCell class design a class that works for any type of Object. use inheritance all objects are subclasses of Object.

public class MemoryCell { public Object read( ) { return storedValue; } public void write( Object x ) { storedValue = x; } private Object storedValue; }

Generic Objects in Java


two problem: 1) Although all objects are subclasses of Object, the primitive types boolean, short, char, byte, int, long, float, double are not objects. Thus we cannot directly use MemoryCell to store a primitive value. We must use wrapper class provide by Jave. Wrapper class store a single primitive value and can be used wherever an Object is need. the wrapper class provides a method that can be used to access the primitive value it stores. For the Integer wrapper, this method is named intValue.

Generic Objects in Java


public class Integer { public Integer( int x) { value = x; } public int intValue( ) { return value; } private int value; }

Generic Objects in Java


2) the read method for MemoryCell returns an Object. To get the int value that is hidden inside the Integer object, we must convert the result of read back to an Integer , and then use mathod intValue access the value . This involves using a type conversion.

Generic Objects in Java


public class TestMemoryCell { public static void main( String [ ] args ) { MemoryCell m = new MemoryCell ( ) ; m.write( new Integer ( 5 ) ); System.out.println( Contents are : + ( (Integer) m.read( ) ). intValue( ) ); } }

Generic Objects in Java


3. Implementing Generic findMax The MemoryCell class required no special properties of Object ; the only operations performed were reference assignments, which are always available. Finding the maximum item in an array of items does require a special property; we must be able to compare two items and decide whch is larger.

Generic Objects in Java


Comparable findMax ( Comparable [ ] a ) { Comparable maxValue = a[ 0 ]; for ( int i = 1; i < a.length; i++ ) if ( maxValue.lessThan ( a[i] ) ) maxValue = a[i]; return maxValue; }

a generic findMax algorithm.


Notice that the objects that are manipulated are not Object, But instead are Comparable.

Generic Objects in Java


Comparable is an interface.
In java, an interface declares a set of methods that must be implemented. In this example, any class that is Comparable must provide an implementation of lessThan A class that is Comparable must also declare so by using the implements clause.

public interface Comparable { int lessThan( Comparable rhs ); } compareTo

Generic Objects in Java


comparable findMax ( Comparable [ ] a ) { Comparable maxValue = a[ 0 ]; for ( int i = 1; i < a.length; i++ ) if ( maxValue.compareTo(a[i])<0 ) maxValue = a[i]; return maxValue; } a generic findMax algorithm.

Generic Objects in Java


another Example:
public interface Comparable { public int compareTo(object o ); } public class Max { public static Comparable max( comparable o1, comparable o2 ) { if ( o1. compareTo( o2 ) > 0 ) return o1; else return o2; } }

Generic Objects in Java


class Circle { private double radius; public Circle( ) { radius = 1.0; } public Circle( double r ) { radius = r ; } public double getRadius ( ) { return radius; } public void set Radius( double newRadius ) { radius = newRadius; } public double findArea( ) { return radius * radius*3.14159; } }

Generic Objects in Java


class ComparableCircle extends Circle implements Comparable { public ComparableCircle ( double r ) { super ( r ); } public int compareTo (object o ) { if ( getRadius( ) > ( ( Circle ) o ) . Getradius ( ) ) return 1; else if ( getRadius ( ) < ( ( Circle ) o ) . GetRadius ( ) ) return 1; else return 0; } }

Generic Objects in Java


public class TestInterface { public static void main( String[ ] args ) { ComparableCircle circle1 = new ComparableCircle( 5 ); ComparableCircle circle2 = new ComparableCircle( 4 ); Comparable circle = Max . max (circle1, circle2 ); System.out.println ( The max circles radius is + ( ( Circle ) circle ) . getRadius ( ) ); System.out.println ( circle ); } }

Exceptions
try { } catch(Exception e) { System.out.println (e); } main ( ) { . f ( ); . } f() { g(); .. . } g() {

Exceptions
Java

1.

error
error, error, error 1) error
2) error 0, 3) error

Exceptions
2. error () 1) (error)------OS (out of Memory) 2) (exception)------OS 0, 3. Java 1)

Exceptions
try { 1 // } catch( ) { 2 // } finally { 3 // }

public class Try2 { public static void main( string args[ ]) { int i = 0; int a[ ] = { 5,6,7,8}; for( i = 0; i < 5; i++) { try { system.out.print(a[ + i + ]/ + i + = + (a[i]/i)); } catch(ArrayIndexOutOfBoundsException e) { system.out.print(); } catch( ArithmeticException e) { system.out.print() } catch(Exception e) { system.out.print( + e.getMessage( ) + ! ); // } finally { system.out.println( i = +i ); } } //for system.out.println( } }

Exceptions

Exceptions
i = 0 a[1]/1 = 6 i = 1 a[2]/2 = 3 i = 2 a[3]/3 = 2 i = 3 i = 4

Exceptions
2) throw throwtry example public void set(int age) { if(age > 0 && age < 100 ) this.age = age ; else throw new Exaption ( IllegaAgeData ) ; // }

Exceptions
throws example public void removeAny( ) throws Underflow { if ( isEmpty( ) ) throw new Underflow( ); . }

Input and Output


import java.io.* 1. Basic Stream Operations System.in standard input; System.out standard output System.err standard error output in java :is done almost exclusively by String concatenation, with no built-in formatting. input in java : reading formatted input is to read a single line into a String object using readLine. The readLine method reads until it encounters a line terminator or end of file. To use readLine, we must first construct a BufferedReader object from an InputStreamReader object that itself constructed from System.in.

Input and Output


import java.io.*; public class DivideByTwo { public static void main( String [ ] args ) { bufferedReader in = new BufferedReader( new InputStreamReader ( System.in ) ); int x; String oneLine; System.out.println( Enter an integer: ); try { oneLine = in.readLine( ); // IOException x = Integer.parseInt( oneLine ); //NumberFormatException System.out.println( Half of x is + ( x/2) ); } catch( Exception e ) { system.out.println( e ); } } }

Input and Output


Recall that to read a single primitive type, such as an int: 1) use readLine to read the line as a String. 2) then apply a method to generate the primitive type from the String. For int , we can use parseInt.

2. The StringTokenizer Object


Sometimes we have several items on a line. For instance, suppose each line has two ints . Java provides the StringTokenizer object to separate a String into tokens.

Input and Output import java.io.* import java.utl.*; public class MaxTest { public static void main( String [ ] args ) { BufferedReader in = new BufferedReader ( new InputStreamReader( System.in ) ); String oneLine; StringTokenizer str; int x; int y; System.out.println( Enter 2 ints on one line: ); try { oneLine = in.readLine( ); str = new StringTokenizer( oneLine ); if( str . countTokens( ) != 2 ) throw new NumberFormatException( ); x = Integer . parseInt( str . nextToken( ) ); y = Integer . parseInt( str . nextToken( ) ); System.out.println( Max: + Math.max( x, y ) ) ; } catch ( Exception e ) { System.err.println( Error: need two ints ); } } }

Input and Output


To use StringTokenizer , provide the Import directive import java.util.*; By default, tokens are separated by white space.

example: I am learning Java now

Input and Output


3. Sequential Files One of the basic rules of java is that what works for terminal I/O as works for files. To deal with a file: System.in-------> InputstringReader--------> BufferedReader filename------->
construct construct construct

FileReader

construct

--------> BufferedReader

Input and Output


import java.io.*; public class ListFiles { public static void main( String [ ] args ) { if( args.length = = 0 ) System.out.println( No files specified ); for( int i = 0; i < args.length; i++ ) listFile( args[ i ] ); } public static void listFile( String fileName ) { FileReader theFile; BufferedReader fileIn = null; String oneLine; Systnm.out.println( FILE: + fileName );

Input and Output


try { theFile = new FileReader( fileName ); fileIn = new BufferedReader( theFile ); while( ( oneLine = fineIn.readLine( ) ) != null ) System.out.println( oneLine ); } catch( exception e ) { System.out.println( e ); } // close the stream try { if( fileIn != null ) fileIn.close( ); } catch( IOException e ) { } } }

Code Organization
1. Packages package DataStructures; Most of our classes will be found in a package named DataStructures. This includes the Overflow and Underflow exception classes.

Code Organization
2. The MyInteger Class public class MyInteger implements Comparable { public MyInteger( int x ) { value = x; } public int intValue( ) { return value; } public int compareTo( comparable rhs ) { return value < ( ( MyInteger ) rhs ) . value ? 1: value = = ( ( MyInteger ) rhs ) . value ? 0 : 1; } private int value; } 3 Efficiency Considerations

Chapter 1
Exercises: (English) P26: 1.5, 1.6 (Chinese) P22: 1.5, 1.6
a[n] 1a 2n

Chapter 1
:
1. 1, 2, , n r, . : n = 5 1 2 3 4 5 r=3 5 4 3 5 4 2 5 4 1 5 3 2 5 3 1 5 2 1 4 3 2 4 3 1 4 2 1 3 2 1 2. Hanoi

Generic Objects in Java


Problem: program1.1: int Abc(int a,int b,int c) {return a+b+b*c+(a+b-c)/(a+b)+4; program1.2: float Abc(float a,float b,float c) {return a+b+b*c+(a+b-c)/(a+b)+4;

Generic Objects in Java program1.1 and 1.2 differ only in the data type of the formal parameters and of the value returned. We can write a generic code in which the data type is a variable whose value is determined by the compiler.This generic code is written using the template statement in program1.3

Generic Objects in Java Program1.3 template<class T> T Abc(T a,T b,T c) {return a+b+b*c+(a+b-c)/(a+b)+4; } From this generic code the compiler can construct 1.1 by substituting int for T and 1.2 by substituting float for T.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy