+ All Categories
Home > Documents > Xiaoyan Li, 2007 1 CSC211 Data Structures Lecture 1: Introduction Instructor: Prof. Xiaoyan Li...

Xiaoyan Li, 2007 1 CSC211 Data Structures Lecture 1: Introduction Instructor: Prof. Xiaoyan Li...

Date post: 30-Dec-2015
Category:
Upload: gilbert-gerald-blake
View: 228 times
Download: 2 times
Share this document with a friend
52
Xiaoyan Li, 2007 Xiaoyan Li, 2007 1 CSC211 Data Structures Lecture 1: Lecture 1: Introduction Introduction Instructor: Prof. Xiaoyan Instructor: Prof. Xiaoyan Li Li Department of Computer Department of Computer Science Science
Transcript

Xiaoyan Li, 2007Xiaoyan Li, 2007 11

CSC211 Data Structures CSC211 Data Structures

Lecture 1: IntroductionLecture 1: Introduction

Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan Li

Department of Computer Science Department of Computer Science

Mount Holyoke CollegeMount Holyoke College

Xiaoyan Li, 2007Xiaoyan Li, 2007 22

Outline of this lectureOutline of this lecture

Course Objectives and ScheduleCourse Objectives and Schedule WHAT (Topics)WHAT (Topics) WHY (Importance)WHY (Importance) WHERE (Goals)WHERE (Goals) HOW (Information and Schedule)HOW (Information and Schedule)

The Phase of Software DevelopmentThe Phase of Software Development Basic design strategyBasic design strategy Pre-conditions and post-conditionsPre-conditions and post-conditions Running time analysisRunning time analysis

Xiaoyan Li, 2007Xiaoyan Li, 2007 33

Topics (WHAT)Topics (WHAT)

Data Structures Data Structures specification, design, implementation and use ofspecification, design, implementation and use of

basic data types (arrays, lists, queues, stacks, trees…)basic data types (arrays, lists, queues, stacks, trees…)

OOP and C++OOP and C++ C++ classes, container classes , Big ThreeC++ classes, container classes , Big Three

Standard Template Library (STL)Standard Template Library (STL) templates, iteratorstemplates, iterators ADTs in our DS course cut-down version of STL ADTs in our DS course cut-down version of STL

Recursion, Searching and Sorting AlgorithmsRecursion, Searching and Sorting Algorithms important techniques in many applications important techniques in many applications

Xiaoyan Li, 2007Xiaoyan Li, 2007 44

Importance (WHY)Importance (WHY)

Data Structures (Data Structures (how to organize datahow to organize data) and ) and Algorithms (Algorithms (how to manipulate datahow to manipulate data) are the cores of ) are the cores of today’s computer programmingtoday’s computer programming

The behavior of Abstract Data Types (The behavior of Abstract Data Types (ADTsADTs) in our ) in our Date Structures course is a cut-down version of Date Structures course is a cut-down version of Standard Template Library (Standard Template Library (STLSTL) in C++) in C++

Lay a foundation for other aspects of “real Lay a foundation for other aspects of “real programming” – programming” – OOP, Recursion, Sorting, SearchingOOP, Recursion, Sorting, Searching

Xiaoyan Li, 2007Xiaoyan Li, 2007 55

Goals (WHERE)Goals (WHERE)

Implement these data structures as classes in C++Implement these data structures as classes in C++ Determine which structures are appropriate in Determine which structures are appropriate in

various situationsvarious situations Confidently learn new structures beyond what are Confidently learn new structures beyond what are

presented in this classpresented in this class also learn part of the OOP and software also learn part of the OOP and software

development methodologydevelopment methodology

understand the data types inside outunderstand the data types inside out

Xiaoyan Li, 2007Xiaoyan Li, 2007 66

Course Information (HOW)Course Information (HOW) ObjectivesObjectives

Data Structures, with C++ and Software EngineeringData Structures, with C++ and Software Engineering

Textbook and ReferencesTextbook and References Texbook: Texbook: Data Structures and Other Objects Using C++ , Third Edition by Data Structures and Other Objects Using C++ , Third Edition by Michael Main Michael Main

and and Walter Walter SavitchSavitch Reference: Reference: C++ How to ProgramC++ How to Program by Dietel & Dietel, 3rd Ed., Prentice Hall 2001 by Dietel & Dietel, 3rd Ed., Prentice Hall 2001

PrerequisitesPrerequisites CS101, Programming; CS102 , OOPCS101, Programming; CS102 , OOP

Assignments and GradingAssignments and Grading 6-7 programming assignments6-7 programming assignments roughly every 2 weeks (30%) roughly every 2 weeks (30%) 3 in-class writing exams3 in-class writing exams (60%), several in-class quizzes (10%) (60%), several in-class quizzes (10%)

Computing FacilitiesComputing Facilities Microsoft Visual Studio C++ (in CS Lab or Visil Lab)Microsoft Visual Studio C++ (in CS Lab or Visil Lab) GNU g++ (Free downloadable to your own machines)GNU g++ (Free downloadable to your own machines)

Xiaoyan Li, 2007Xiaoyan Li, 2007 77

Tentative Schedule (HOW)

( 28 classes = 22 lectures + 3 reviews + 3 exams, 6-7 assignments)

Tentative Schedule (HOW)

( 28 classes = 22 lectures + 3 reviews + 3 exams, 6-7 assignments)

Lecture 1. The Phase of Software Development (Ch 1)Lecture 1. The Phase of Software Development (Ch 1) Lectures 2-3. ADT and C++ Classes (Ch 2)Lectures 2-3. ADT and C++ Classes (Ch 2) Lecture 4-5. Container Classes (Ch 3)Lecture 4-5. Container Classes (Ch 3) Lectures 6-8. Pointers and Dynamic Arrays (Ch 4)Lectures 6-8. Pointers and Dynamic Arrays (Ch 4) Reviews and the 1st exam (Ch. 1-4, after mid-semester break)Reviews and the 1st exam (Ch. 1-4, after mid-semester break) Lectures 9-10. Linked Lists (Ch. 5)Lectures 9-10. Linked Lists (Ch. 5) Lectures 11. Template and STL (Ch 6)Lectures 11. Template and STL (Ch 6) Lecture 12. Stacks (Ch 7) and Queues (Ch 8)Lecture 12. Stacks (Ch 7) and Queues (Ch 8) Lectures 13-14. Recursion (Ch 9)Lectures 13-14. Recursion (Ch 9) Reviews and the 2nd exam (Ch. 5-9, before Thanksgiving)Reviews and the 2nd exam (Ch. 5-9, before Thanksgiving) Lectures 15-18. Trees (Ch 10, Ch 11)Lectures 15-18. Trees (Ch 10, Ch 11) Lectures 19-20. Searching and Hashing (Ch 12)Lectures 19-20. Searching and Hashing (Ch 12) Lectures 21- 22. Sorting (Ch 13) Lectures 21- 22. Sorting (Ch 13) Reviews and the 3rd exam (mainly Ch. 10-13, Reviews and the 3rd exam (mainly Ch. 10-13, Dec 15-19Dec 15-19 ))

Xiaoyan Li, 2007Xiaoyan Li, 2007 88

Course Web PageCourse Web Page

You can find all the information atYou can find all the information at

http://www.mtholyoke.edu/courses/xli/CS211/CS211-Fall2007.htmlhttp://www.mtholyoke.edu/courses/xli/CS211/CS211-Fall2007.html

-Come back frequently for the updating of lecture schedule, Come back frequently for the updating of lecture schedule, programming assignments and exam scheduleprogramming assignments and exam schedule

- Reading assignments & programming assignmentsReading assignments & programming assignments

Xiaoyan Li, 2007Xiaoyan Li, 2007 99

OutlineOutline

Course Objectives and ScheduleCourse Objectives and Schedule InformationInformation TopicsTopics ScheduleSchedule

The Phase of Software DevelopmentThe Phase of Software Development Basic design strategyBasic design strategy Pre-conditions and post-conditionsPre-conditions and post-conditions Running time analysisRunning time analysis

Xiaoyan Li, 2007Xiaoyan Li, 2007 1010

Phase of Software Development Phase of Software Development

Basic Design Strategy – four steps (Reading: Ch.1 )Basic Design Strategy – four steps (Reading: Ch.1 ) Specify the problem - Input/Output (I/O) Specify the problem - Input/Output (I/O) Design data structures and algorithms (Design data structures and algorithms (pseudo codepseudo code)) Implement in a language such as C++Implement in a language such as C++ Test and debug the program (Reading Ch 1.3)Test and debug the program (Reading Ch 1.3)

Design TechniqueDesign Technique Decomposing the problemDecomposing the problem

Two Important Issues (along with design and Two Important Issues (along with design and Implement)Implement) Pre-Conditions and Post-ConditionsPre-Conditions and Post-Conditions Running Time AnalysisRunning Time Analysis

Xiaoyan Li, 2007Xiaoyan Li, 2007 1111

An important topic: An important topic: preconditionspreconditions and and postconditionspostconditions..

They are a method of specifying what a They are a method of specifying what a function accomplishes.function accomplishes.

Preconditions and PostconditionsPreconditions and Postconditions

Precondition and Postcondition Presentation copyright 1997, Addison Wesley LongmanPrecondition and Postcondition Presentation copyright 1997, Addison Wesley LongmanFor use with For use with Data Structures and Other Objects Using C++ Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch.by Michael Main and Walter Savitch.

Xiaoyan Li, 2007Xiaoyan Li, 2007 1212

Preconditions and PostconditionsPreconditions and Postconditions

Frequently a programmer must communicate Frequently a programmer must communicate precisely precisely whatwhat a function accomplishes, a function accomplishes, without any indication of without any indication of howhow the function the function does its work.does its work.

Can you think of a situationCan you think of a situationwhere this would occur ?where this would occur ?

Xiaoyan Li, 2007Xiaoyan Li, 2007 1313

ExampleExample

You are the head of a You are the head of a programming team programming team and you want one of and you want one of your programmers to your programmers to write a function for write a function for part of a project.part of a project.

HERE ARETHE REQUIREMENTS

FOR A FUNCTION THAT IWANT YOU TO

WRITE.

I DON'T CAREWHAT METHOD THE

FUNCTION USES,AS LONG AS THESE

REQUIREMENTSARE MET.

Xiaoyan Li, 2007Xiaoyan Li, 2007 1414

What are Preconditions and Postconditions?What are Preconditions and Postconditions?

One way to specify such requirements is One way to specify such requirements is with a pair of statements about the function.with a pair of statements about the function.

The The preconditionprecondition statement indicates what statement indicates what must be true before the function is called.must be true before the function is called.

The The postconditionpostcondition statement indicates what statement indicates what will be true when the function finishes its will be true when the function finishes its work.work.

Xiaoyan Li, 2007Xiaoyan Li, 2007 1515

ExampleExample

void write_sqrt( double x)

// Precondition: x >= 0.// Postcondition: The square root of x has// been written to the standard output.

...

Xiaoyan Li, 2007Xiaoyan Li, 2007 1616

ExampleExample

void write_sqrt( double x)

// Precondition: x >= 0.// Postcondition: The square root of x has// been written to the standard output.

...}

The precondition and The precondition and postcondition appear as postcondition appear as comments in your program.comments in your program.

They are usually placed after the They are usually placed after the function’s parameter list.function’s parameter list.

Xiaoyan Li, 2007Xiaoyan Li, 2007 1717

ExampleExample

void write_sqrt( double x)

// Precondition: x >= 0.// Postcondition: The square root of x has// been written to the standard output.

...}

In this example, the precondition In this example, the precondition requires thatrequires that

x >= 0x >= 0 be true whenever the function is be true whenever the function is

called.called.

Xiaoyan Li, 2007Xiaoyan Li, 2007 1818

ExampleExample

write_sqrt( -10 );write_sqrt( 0 );write_sqrt( 5.6 );

Which of these function callsWhich of these function callsmeet the precondition ?meet the precondition ?

Xiaoyan Li, 2007Xiaoyan Li, 2007 1919

ExampleExample

Which of these function callsWhich of these function callsmeet the precondition ?meet the precondition ?

The second and third calls are fine, sinceThe second and third calls are fine, sincethe argument is greater than or equal to zero.the argument is greater than or equal to zero.

write_sqrt( -10 );write_sqrt( 0 );write_sqrt( 5.6 );

Xiaoyan Li, 2007Xiaoyan Li, 2007 2020

ExampleExample

Which of these function callsWhich of these function callsmeet the precondition ?meet the precondition ?

But the first call violates the precondition,But the first call violates the precondition,since the argument is less than zero.since the argument is less than zero.

write_sqrt( -10 );write_sqrt( 0 );write_sqrt( 5.6 );

Xiaoyan Li, 2007Xiaoyan Li, 2007 2121

ExampleExample

void write_sqrt( double x)

// Precondition: x >= 0.// Postcondition: The square root of x has// been written to the standard output.

...}

The postcondition always indicates The postcondition always indicates what work the function has what work the function has accomplished. In this case, when accomplished. In this case, when the function returns the square root the function returns the square root of of xx has been written. has been written.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2222

Another ExampleAnother Example

bool is_vowel( char letter )// Precondition: letter is an uppercase or// lowercase letter (in the range 'A' ... 'Z' or 'a' ... 'z') .// Postcondition: The value returned by the// function is true if letter is a vowel;// otherwise the value returned by the function is// false.

...

Xiaoyan Li, 2007Xiaoyan Li, 2007 2323

Another ExampleAnother Example

is_vowel( 'A' );is_vowel(' Z' );is_vowel( '?' );

What values will be returnedWhat values will be returnedby these function calls ?by these function calls ?

Xiaoyan Li, 2007Xiaoyan Li, 2007 2424

Another ExampleAnother Example

is_vowel( 'A' );is_vowel(' Z' );is_vowel( '?' );

What values will be returnedWhat values will be returnedby these function calls ?by these function calls ? truetrue

falsefalse

Nobody knows, because theNobody knows, because theprecondition has been violated.precondition has been violated.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2525

Consequence of ViolationConsequence of Violation

write_sqrt(-10.0);is_vowel( '?' );

Who are responsible for the crash ?Who are responsible for the crash ?

Violating the preconditionViolating the preconditionmight even crash the computer.might even crash the computer.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2626

Always make sure the precondition is valid . . .Always make sure the precondition is valid . . .

The programmer who The programmer who calls the function is calls the function is responsible for responsible for ensuring that the ensuring that the precondition is valid precondition is valid when the function is when the function is called.called.

AT THIS POINT, MYPROGRAM CALLS YOURFUNCTION, AND I MAKE

SURE THAT THEPRECONDITION IS

VALID.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2727

. . . so the postcondition becomes true at the function’s end. . . . so the postcondition becomes true at the function’s end.

The programmer who The programmer who writes the function counts writes the function counts on the precondition being on the precondition being valid, and valid, and ensures that the ensures that the postcondition becomes postcondition becomes true true at the function’s end.at the function’s end.

THEN MY FUNCTIONWILL EXECUTE, AND WHEN

IT IS DONE, THEPOSTCONDITION WILL BE

TRUE.I GUARANTEE IT.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2828

A QuizA Quiz

Suppose that you call Suppose that you call a function, and you a function, and you neglect to make sure neglect to make sure that the precondition that the precondition is valid. is valid. Who Who is responsible if this is responsible if this inadvertently causes a inadvertently causes a 1-day long blackout in 1-day long blackout in NYC or other disaster?NYC or other disaster?

YouYouThe programmer who The programmer who

wrote that Power wrote that Power Supply functionSupply function

Mayor BloombergMayor Bloomberg

Out of Pen StationOut of Pen Station

The famous skyline was dark on Aug 14th, 2003.

Xiaoyan Li, 2007Xiaoyan Li, 2007 2929

A QuizA Quiz

Suppose that you call Suppose that you call a function, and you a function, and you neglect to make sure neglect to make sure that the precondition that the precondition is valid. is valid. Who Who is responsible if this is responsible if this inadvertently causes a inadvertently causes a 1-day long blackout in 1-day long blackout in NYC or other disaster?NYC or other disaster?

YouYou

The programmer who The programmer who calls a function is calls a function is responsible for responsible for ensuring that the ensuring that the precondition is valid.precondition is valid.

Out of Pen StationOut of Pen Station

Xiaoyan Li, 2007Xiaoyan Li, 2007 3030

On the other hand, careful programmers also follow these rules:On the other hand, careful programmers also follow these rules:

When you write a function, you should When you write a function, you should make every effort to detect when a make every effort to detect when a precondition has been violated.precondition has been violated.

If you detect that a precondition has been If you detect that a precondition has been violated, then print an error message and violated, then print an error message and halt the program.halt the program.

Xiaoyan Li, 2007Xiaoyan Li, 2007 3131

On the other hand, careful programmers also follow these rules:On the other hand, careful programmers also follow these rules:

When you write a function, you should When you write a function, you should make every effort to detect when a make every effort to detect when a precondition has been violated.precondition has been violated.

If you detect that a precondition has been If you detect that a precondition has been violated, then print an error message and violated, then print an error message and halt the program...halt the program...

...rather than causing...rather than causing

a chaos.a chaos.The famous skyline was dark on Aug 14th, 2003.

Xiaoyan Li, 2007Xiaoyan Li, 2007 3232

ExampleExample

void write_sqrt( double x)// Precondition: x >= 0.// Postcondition: The square root of x has// been written to the standard output.{ assert(x >= 0);

... The assert function The assert function (described in Section 1.1) is (described in Section 1.1) is useful for detecting violations useful for detecting violations of a precondition.of a precondition.

Xiaoyan Li, 2007Xiaoyan Li, 2007 3333

Advantages of Using Pre- and Post-conditionsAdvantages of Using Pre- and Post-conditions

Concisely describes the behavior of a Concisely describes the behavior of a function...function...

... without cluttering up your thinking with ... without cluttering up your thinking with details of how the function works.details of how the function works.

At a later point, you may reimplement the At a later point, you may reimplement the function in a new way ...function in a new way ...

... but programs (which only depend on the ... but programs (which only depend on the precondition/postcondition) will still work precondition/postcondition) will still work with no changes.with no changes.

Xiaoyan Li, 2007Xiaoyan Li, 2007 3434

PreconditionPrecondition The programmer who calls The programmer who calls

a function ensures that the a function ensures that the precondition is valid.precondition is valid.

The programmer who The programmer who writes a function can bank writes a function can bank on the precondition being on the precondition being true when the function true when the function begins execution.begins execution.

PostconditionPostcondition The programmer The programmer

who writes a who writes a function ensures function ensures that the that the postcondition is postcondition is true when the true when the function finishes function finishes executing.executing.

Summary of pre- and post-conditionsSummary of pre- and post-conditions

Xiaoyan Li, 2007Xiaoyan Li, 2007 3535

Phase of Software Development Phase of Software Development

Basic Design Strategy – four steps (Reading: Ch.1 )Basic Design Strategy – four steps (Reading: Ch.1 ) Specify Input/Output (I/O) Specify Input/Output (I/O) Design data structures and algorithmsDesign data structures and algorithms Implement in a language such as C++Implement in a language such as C++ Test and debug the program (Reading Ch 1.3)Test and debug the program (Reading Ch 1.3)

Design Technique Design Technique Decomposing the problemDecomposing the problem

Two Important Issues (along with design and Two Important Issues (along with design and Implement)Implement) Pre-Conditions and Post-ConditionsPre-Conditions and Post-Conditions Running Time AnalysisRunning Time Analysis

Xiaoyan Li, 2007Xiaoyan Li, 2007 3636

Running Time Analysis – Big ORunning Time Analysis – Big O

Time Analysis Time Analysis Fast enough?Fast enough? How much longer if input gets larger?How much longer if input gets larger? Which among several is the fastest?Which among several is the fastest?

Xiaoyan Li, 2007Xiaoyan Li, 2007 3737

Example : Stair Counting ProblemExample : Stair Counting Problem

How many steps ?How many steps ?

Find it out yourself !Find it out yourself !

Eiffel TowerEiffel Tower

1789 (Birnbaum)

1671 (Joseph Harriss)

1652 (others)

1665 (Official Eiffel Tower Website)

Xiaoyan Li, 2007Xiaoyan Li, 2007 3838

Example : Stair Counting ProblemExample : Stair Counting Problem

Find it out yourself !Find it out yourself ! Method 1: Walk down and keep Method 1: Walk down and keep

a tallya tally

Method 2 : Walk down, but let Method 2 : Walk down, but let Judy keep the tallyJudy keep the tally

Method 3: Jervis to the rescueMethod 3: Jervis to the rescue

Eiffel TowerEiffel Tower

II y a II y a 2689 2689 marches marches dan cet dan cet escalier escalier ______________

vraiment!vraiment!

共有共有

2689 2689

级台阶级台阶______________

千真万千真万确确 !!

Down+1, hat, back, Judy make a markDown+1, hat, back, Judy make a mark

Each time a step down, make a markEach time a step down, make a mark

One mark per digit One mark per digit

There are There are 2689 2689

steps in steps in this this

stairway stairway

____________

(really!)(really!)

Xiaoyan Li, 2007Xiaoyan Li, 2007 3939

Example : Stair Counting ProblemExample : Stair Counting Problem

How to measure the time?How to measure the time? Just measure the actual time Just measure the actual time

vary from person to personvary from person to person depending on many factorsdepending on many factors

Count certain operationsCount certain operations each time walk up/down, 1 each time walk up/down, 1

operationoperation each time mark a symbol, 1 each time mark a symbol, 1

operationoperation

Eiffel TowerEiffel Tower

Xiaoyan Li, 2007Xiaoyan Li, 2007 4040

Example : Stair Counting ProblemExample : Stair Counting Problem

Find it out yourself !Find it out yourself ! Method 1: Walk down and keep a tallyMethod 1: Walk down and keep a tally

Method 2 : Walk down, let Judy keep tallyMethod 2 : Walk down, let Judy keep tally

Method 3: Jervis to the rescueMethod 3: Jervis to the rescueEiffel TowerEiffel Toweronly 4 marks !only 4 marks !

2689 (down) + 2689 (up) + 2689 (marks) 2689 (down) + 2689 (up) + 2689 (marks) = 8067= 8067

Down: 3,616,705 = 1+2+…+2689 Down: 3,616,705 = 1+2+…+2689

Up: 3,616,705 = 1+2+…+2689Up: 3,616,705 = 1+2+…+2689

Marks: 2,689 = 1+1+…+1Marks: 2,689 = 1+1+…+1

7,236,099 !7,236,099 !

Xiaoyan Li, 2007Xiaoyan Li, 2007 4141

Example : Stair Counting ProblemExample : Stair Counting Problem

Size of the Input : nSize of the Input : n Method 1: Walk down and keep a tallyMethod 1: Walk down and keep a tally

Method 2 : Walk down, let Judy keep tallyMethod 2 : Walk down, let Judy keep tally

Trick: Compute twice the amount Trick: Compute twice the amount and then divided by twoand then divided by two

Method 3: Jervis to the rescueMethod 3: Jervis to the rescue

Eiffel TowerEiffel TowerThe number of digits in n = [logThe number of digits in n = [log1010 n]+1 n]+1

3n3n

n+2(1+2+…+n) = n+(n+1)n = nn+2(1+2+…+n) = n+(n+1)n = n22+2n+2n

Xiaoyan Li, 2007Xiaoyan Li, 2007 4242

Example : Stair Counting ProblemExample : Stair Counting Problem

Big-O Notation – the order of the algorithmBig-O Notation – the order of the algorithm Use the largest term in a formulaUse the largest term in a formula Ignore the multiplicative constantIgnore the multiplicative constant

Method 1: Linear timeMethod 1: Linear time

Method 2 : Quadratic timeMethod 2 : Quadratic time

Method 3: Logarithmic timeMethod 3: Logarithmic time

Eiffel TowerEiffel Tower

[log[log1010 n]+1 => O(log n) n]+1 => O(log n)

3n => O(n)3n => O(n)

nn22+2n => O(n+2n => O(n22))

Xiaoyan Li, 2007Xiaoyan Li, 2007 4343

A Quiz A Quiz

Big-O notationBig-O notation

O(nO(n22))

O(nO(n22))

O(nO(n22))

O(n)O(n)

O(log n)O(log n)

Number of operationsNumber of operations

nn22+5n+5n

100n+n100n+n22

(n+7)(n-2)(n+7)(n-2)

n+100n+100

number of digits in 2nnumber of digits in 2n

Xiaoyan Li, 2007Xiaoyan Li, 2007 4444

Big-O NotationBig-O Notation

The order of an algorithm generally is more The order of an algorithm generally is more important than the speed of the processorimportant than the speed of the processor

Input size: nInput size: n O(log n)O(log n) O (n)O (n) O (nO (n22))

# of stairs: n# of stairs: n [log[log1010n]+1n]+1 3n3n nn22+2n+2n

1010 22 3030 120120

100100 33 300300 10,20010,200

10001000 44 30003000 1,002,0001,002,000

Xiaoyan Li, 2007Xiaoyan Li, 2007 4545

Time Analysis of C++ FunctionsTime Analysis of C++ Functions

Example- Example- Quiz ( 5 minutes)Quiz ( 5 minutes) Printout all items in an integer array of size NPrintout all items in an integer array of size N

Frequent linear patternFrequent linear pattern A loop that does a fixed amount of operations N times A loop that does a fixed amount of operations N times

requires O(N) timerequires O(N) time

for (i=0; i< N; i++ )for (i=0; i< N; i++ ){{

val = a[i];val = a[i];cout << val;cout << val;

}}

2 C++ 2 C++ operations or operations or more?more?

Xiaoyan Li, 2007Xiaoyan Li, 2007 4646

Time Analysis of C++ FunctionsTime Analysis of C++ Functions

Another exampleAnother example Printout char one by one in a string of length NPrintout char one by one in a string of length N

What is a single operation?What is a single operation? If the function calls do complex things, then count the If the function calls do complex things, then count the

operation carried out thereoperation carried out there Put a function call outside the loop if you can!Put a function call outside the loop if you can!

for (i=0; i< strlen(str); i++ )for (i=0; i< strlen(str); i++ ){{

c = str[i];c = str[i];cout << c;cout << c;

}}

O(NO(N22)!)!

Xiaoyan Li, 2007Xiaoyan Li, 2007 4747

Time Analysis of C++ FunctionsTime Analysis of C++ Functions

Another exampleAnother example Printout char one by one in a string of length NPrintout char one by one in a string of length N

What is a single operation?What is a single operation? If the function calls do complex things, then count the If the function calls do complex things, then count the

operation carried out thereoperation carried out there Put a function call outside the loop if you can!Put a function call outside the loop if you can!

N = strlen(str);N = strlen(str);for (i=0; i<N; i++ )for (i=0; i<N; i++ ){{

c = str[i];c = str[i];cout << c;cout << c;

}}

O(N)!O(N)!

Xiaoyan Li, 2007Xiaoyan Li, 2007 4848

Time Analysis of C++ FunctionsTime Analysis of C++ Functions

Worst case, average case and best case Worst case, average case and best case search a number x in an integer array a of size Nsearch a number x in an integer array a of size N

Can you provide an exact number of operations?Can you provide an exact number of operations? Best case: 1+2+1Best case: 1+2+1 Worst case: 1+3N+1Worst case: 1+3N+1 Average case: 1+3N/2+1Average case: 1+3N/2+1

for (i=0; (i< N) && (a[i] != x); i++ );for (i=0; (i< N) && (a[i] != x); i++ );

if (i < N) cout << “Number ” << x << “is at location ” << i << endl;if (i < N) cout << “Number ” << x << “is at location ” << i << endl;else cout << “Not Found!” << endl;else cout << “Not Found!” << endl;

Xiaoyan Li, 2007Xiaoyan Li, 2007 4949

Testing and DebuggingTesting and Debugging

Test: run a program and observe its behaviorTest: run a program and observe its behavior input -> expected output?input -> expected output? how long ?how long ? software engineering issuessoftware engineering issues

Choosing Test Data : two techniquesChoosing Test Data : two techniques boundary valuesboundary values fully exercising code (tool: profiler)fully exercising code (tool: profiler)

Debugging… find the bug after an error is foundDebugging… find the bug after an error is found rule: never change if you are not sure what’s the errorrule: never change if you are not sure what’s the error tool: debuggertool: debugger

Xiaoyan Li, 2007Xiaoyan Li, 2007 5050

SummarySummary

Often ask yourselves FOUR questionsOften ask yourselves FOUR questions WHAT, WHY, WHERE & HOW WHAT, WHY, WHERE & HOW

Topics – DSs, C++, STL, basic algorithmsTopics – DSs, C++, STL, basic algorithms Data Structure expertsData Structure experts Schedule – 22 lectures, 7 assignments, 3 examsSchedule – 22 lectures, 7 assignments, 3 exams some credits (10) for attending the classsome credits (10) for attending the class Information – websiteInformation – website

Remember and apply two things (Ch 1)Remember and apply two things (Ch 1) Basic design strategyBasic design strategy Pre-conditions and post-conditionsPre-conditions and post-conditions Running time analysisRunning time analysis Testing and Debugging (reading 1.3)Testing and Debugging (reading 1.3)

Xiaoyan Li, 2007Xiaoyan Li, 2007 5151

Reminder … Reminder …

Lecture 2: ADT and C++ ClassesLecture 2: ADT and C++ Classes

Reading Assignment before the next lecture: Reading Assignment before the next lecture:

Chapter 1Chapter 1

Chapter 2, Sections 2.1-2.3 Chapter 2, Sections 2.1-2.3

Office Hours: T,Th 10:00-11:00 AMOffice Hours: T,Th 10:00-11:00 AM(Location: Clapp 227 )(Location: Clapp 227 )

Check website for detailsCheck website for details

Xiaoyan Li, 2007Xiaoyan Li, 2007 5252

THE ENDTHE END


Recommended