coordinación de ciencias...

89
Propedéutico de Programación Coordinación de Ciencias Computacionales Semana 1, Primera parte Dra. Pilar Gómez Gil http://ccc.inaoep.mx/~pgomez/cursos/programacion/ Versión 1.1 270508

Upload: others

Post on 05-Jul-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Propedéutico de Programación

Coordinación de Ciencias

Computacionales

Semana 1,

Primera parte

Dra. Pilar Gómez Gil

http://ccc.inaoep.mx/~pgomez/cursos/programacion/

Versión 1.1 270508

Page 2: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Objetivos del curso

• Revisar conceptos de programación y estructuras de datos con un enfoque orientado a objetos, a través de su implementación en C++.

• Se espera que al final del curso, el/la estudiante muestren un dominio profundo de estos temas.

© P. Gómez Gil. INAOEP 2008

Page 3: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Temario General

• Revisión de fundamentos de programación

• Desarrollo orientado a objetos

• Apuntadores

• Diseño de datos e implementación

• La estructura abstracta lista

• Pilas y Colas

• Árboles

• Otras estructuras

© P. Gómez Gil. INAOEP 2008

Page 4: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Libros • Libros de texto: • 1. Dale, Nell and Weems, Chip. Programming and Problem Solving with

C++. 4th. Edition. Jones and Bartlett Publishers. Boston, 2005. ISBN 10: 0-7637-0798-8

• 2. Dale, Nell. C++ Plus Data Structures. 4th. Edition. Jones and Bartlett Publishers. Boston 2007. ISBN-10: 0-7637-4158-2

• • Otros libros recomendados: • 1. Bruce Eckel. Thinking in C++, Vol 1. 2000 (versión electrónica en

www.Planetpdf.com) • 2. Koffman, Elliot B. Paul A. T. Wolfgang. Objects, Abstraction, Data

Structures and Design using C++. John Wiley, 2006 (disponible en reserva de la biblioteca del INAOE)

• 3. Astrachan, Owen L. Computer Science Tapestry. 2º. Edition. McGraw Hill, 2000. (Disponible en reserva de la biblioteca del INAOE)

• 4. Drozdek, Adam. Data Structures and Algorithms in C++. Thomson, 2005. (Disponible en reserva de la biblioteca del INAOE)

© P. Gómez Gil. INAOEP 2008

Page 5: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Evaluación y Fechas EVALUACIÓN DEL CURSO

• 1 exámenes parcial 50 %

• 1 Examen final 50 %

• Nota: el examen final es acumulativo, incluye todos los temas vistos en el curso.

FECHAS IMPORTANTES

• 1º. día de clases 26 de Mayo 2008

• Examen parcial 18 de Junio 2008

• Examen final 14 de Julio 2008

• Revisión de calificaciones 16 de Julio 2008

© P. Gómez Gil. INAOEP 2008

Page 6: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Plan de trabajo Semana 1

SEMANA SESION FECHA TEMA REFERENCIA

1 1 lunes, 26 de mayo de 2008

1. Revisión de fundamentos de programación

1.1. Principios de Ingeniería de software 1.4 Dale & Weems

1.2. C++ Sintaxis y semántica cap 2

1.3. Condiciones expresiones lógicas, estructuras de selección y ciclos

3 a 6,9

1.4. Funciones 7 y 8

2 miércoles, 28 de mayo de 2008

1.5. Tipos de datos simples cap. 10

1.6. Tipos de datos estructurados cap. 11

1.7. Recursión cap 18

3 viernes, 30 de mayo de 2008

Ejercicio con temas de la semana

© P. Gómez Gil. INAOEP 2008

Page 7: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Tarea 1

• Realizar el ejercicio sugerido para practicar los temas de esta semana, antes de la sesión del viernes.

• El ejercicio se resolverá en la sesión del viernes

© P. Gómez Gil. INAOEP 2008

Page 8: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Dale/Weems Slides based on work by

Sylvia Sorkin, Community College of Baltimore County -

Essex Campus

Page 9: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Problem-Solving Phase

• Analyze the problem and specify what the solution must do

• Develop a general solution(algorithm) to solve the problem

• Verify that your solution really solves the problem

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 10: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

A Tempting Shortcut?

GOAL

THINKING CODE

REVISE REVISE

REVISE

DEBUG

DEBUG

DEBUG

TEST

CODE

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 11: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Three C++ Program Stages

other code

from libraries,

etc.

written in

machine

language

written in

machine

language

written in

C++

via compiler via linker

SOURCE OBJECT EXECUTABLE

myprog.cpp myprog.obj myprog.exe

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 12: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Computing Profession Ethics

• Copy software only with permission from the

copyright holder

• Give credit to another programmer by name

whenever using his/her code

• Use computer resources only with permission

• Guard the privacy of confidential data

• Use software engineering principles to develop

software free from errors Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 13: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

A C++ program is a collection of one or more

functions

• There must be a function called main()

• Execution always begins with the first statement in function main()

• Any other functions in your program are subprograms and are not executed until they are called

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 14: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Program With Several Functions

main function

square function

cube function

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 15: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

C++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 16: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

C++ Simple Data Types

simple types

integral floating

char short int long bool enum float double long double

unsigned

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 17: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Standard Data Types in C++

• Integral Types – represent whole numbers and their negatives

– declared as int, short, or long

• Floating Types – represent real numbers with a decimal point

– declared as float, or double

• Character Types – represent single characters

– declared as char

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 18: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Insertion Operator(<<)

• Variable cout is predefined to denote an output stream that goes to the standard output device(display screen)

• The insertion operator << called “put to” takes 2 operands

• The left operand is a stream expression, such as cout

• The right operand is an expression of a

simple type or a string constant

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 19: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Output Statements

SYNTAX

These examples yield the same output:

cout << “The answer is “;

cout << 3 * 4;

cout << “The answer is “ << 3 * 4;

cout << Expression << Expression . . .;

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 20: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Is compilation the first step? • No; before your source program is compiled,

it is first examined by the preprocessor that

– removes all comments from source code

– handles all preprocessor directives--they begin with the # character such as

#include <iostream>

– This include tells the preprocessor to look in the standard include directory for the header file called iostream and insert its contents into your source code

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 21: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

No I/O is built into C++

• Instead, a library provides an output stream

Screen executing

program

ostream

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 22: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Using Libraries

• A library has 2 parts Interface (stored in a header file) tells

what items are in the library and how to use them

Implementation (stored in another file) contains the definitions of the items in the library

• #include <iostream> Refers to the header file for the iostream

library needed for use of cout and endl.

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 23: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Functions

• Every C++ program must have a function called main

• Program execution always begins with function main

• Any other functions are subprograms and must be called

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 24: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

More About Functions • It is not considered good practice for

the body block of function main to be long

• Function calls are used to do subtasks

• Every C++ function has a return type

• If the return type is not void, the function returns a value to the calling block

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 25: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Where are functions?

Functions are subprograms

– located in libraries, or

–written by programmers for their use in a particular program

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 26: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

26

HEADER FILE FUNCTION EXAMPLE VALUE OF CALL

fabs(x) fabs(-6.4) 6.4

<cmath> pow(x,y) pow(2.0,3.0) 8.0

<cmath> sqrt(x) sqrt(100.0) 10.0

<iomanip> setprecision(n) setprecision(3)

<cmath> log(x) log(2.0) .693147

sqrt(x) sqrt(2.0) 1.41421

<cstdlib> abs(i) abs(-6) 6

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 27: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Function Call

• A function call temporarily transfers control to the called function’s code

• When the function’s code has finished executing, control is transferred back to the calling block

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 28: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

FunctionName =( Argument List )

The argument list is a way for functions to communicate with each other by passing information

The argument list can contain zero, one, or more arguments, separated by

commas, depending on the function

Function Call Syntax

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 29: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

A void function call stands alone #include <iostream> void DisplayMessage(int n); // Declares function

int main() { DisplayMessage(15); // Function call cout << “Good Bye“ << endl; return 0; }

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 30: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Two Kinds of Functions

Always returns

a single value to

its caller and is

called from within

an expression

Never returns a

value to its caller

and is called as a

separate

statement

Value-Returning Void

30 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 31: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

31

<iostream> is header file

• For a library that defines 3 objects

An istream object named cin (keyboard)

An ostream object named cout (screen)

An ostream object named cerr (screen)

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 32: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Extraction Operator(>>)

• Variable cin is predefined to denote an input stream from the standard input device(the keyboard)

• The extraction operator >> called “get from” takes 2 operands; the left operand is a stream expression, such as cin--the right

operand is a variable of simple type

• Operator >> attempts to extract the next item from the input stream and to store its value in the right operand variable

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 33: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

SYNTAX

These examples yield the same result.

cin >> length;

cin >> width;

cin >> length >> width;

Input Statements

cin >> Variable >> Variable . . .;

33 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 34: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

The get() function can be used to

read a single character.

get() obtains the very next character

from the input stream without skipping

any leading whitespace characters

Another Way to Read char

Data

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 35: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

getline() Function

• Because the extraction operator stops reading at the first trailing whitespace, >> cannot be used to input a string with blanks in it

• Use the getline function with 2 arguments to overcome this obstacle

• First argument is an input stream variable, and second argument is a string variable

Example

string message;

getline(cin, message); Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 36: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Disk Files for I/O

your variable

(of type ifstream)

your variable

(of type ofstream)

disk file “myInfile.dat”

disk file “myOut.dat”

executing

program

input data output data

#include <fstream>

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 37: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Disk I/O

To use disk I/O

– Access #include <fstream>

– Choose valid identifiers for your filestreams and declare them

– Open the files and associate them with disk names

– Use your filestream identifiers in your I/O statements(using >> and << , manipulators, get, ignore)

– Close the files

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 38: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Disk I/O Statements

#include <fstream>

ifstream myInfile; // Declarations

ofstream myOutfile;

myInfile.open(“myIn.dat”); // Open files

myOutfile.open(“myOut.dat”);

myInfile.close(); // Close files

myOutfile.close();

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 39: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Opening a File

Opening a file

– Associates the C++ identifier for your file with the physical (disk) name for the file

• If the input file does not exist on disk, open is not successful

• If the output file does not exist on disk, a new file with that name is created

• If the output file already exists, it is erased

– Places a file reading marker at the very beginning of the file, pointing to the first character in the file

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 40: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Stream Fail State

• When a stream enters the fail state,

– Further I/O operations using that stream have no effect at all

– The computer does not automatically halt the program or give any error message

• Possible reasons for entering fail state include

– Invalid input data (often the wrong type)

– Opening an input file that doesn’t exist

– Opening an output file on a disk that is already

full or is write-protected

40 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 41: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Run Time File Name Entry

#include <string>

// Contains conversion function c_str

ifstream inFile;

string fileName;

cout << “Enter input file name: “ << endl; // Prompt

cin >> fileName;

// Convert string fileName to a C string type

inFile.open(fileName.c_str());

41 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 42: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Functional Decomposition

A technique for developing a program in which the

problem is divided into more easily handled

subproblems, the solutions of which create a

solution to the overall problem

In functional decomposition, we work from the

abstract (a list of the major steps in our solution)

to the particular (algorithmic steps that can be

translated directly into code in C++ or another

language)

42 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 43: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Functional Decomposition

Focus is on actions and algorithms

Begins by breaking the solution into a series of major

steps; process continues until each subproblem

cannot be divided further or has an obvious solution

Units are modules representing algorithms

• A module is a collection of concrete and abstract

steps that solves a subproblem

• A module structure chart (hierarchical solution tree)

is often created

Data plays a secondary role in support of actions to be

performed

43 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 44: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Compute

Mileages

Write

Total Miles

Module Structure Chart

Main

Get Data

Round To

Nearest Tenth

Initialize

Total Miles Open Files

44 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 45: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Chapter 5

Conditions, Logical

Expressions, and Selection Control

Structures

Dale/Weems

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 46: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

bool Data Type

• Type bool is a built-in type consisting

of just 2 values, the constants true and false

• We can declare variables of type bool

bool hasFever; // true if has high temperature

bool isSenior; // true if age is at least 55

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 47: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

C++ Control Structures

• Selection

if

if . . . else

switch

• Repetition

for loop

while loop

do . . . while loop Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 48: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Logical

Expression Meaning Description

! p NOT p ! p is false if p is true

! p is true if p is false

p && q p AND q p && q is true if

both p and q are true.

It is false otherwise.

p || q p OR q p || q is true if either

p or q or both are true. It is false

otherwise.

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 49: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

if (Expression)

StatementA

else

StatementB

NOTE: StatementA and StatementB each can be a single statement, a null statement, or a block

If-Then-Else Syntax

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 50: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Nested If Statements

if (Expression1 )

Statement1

else if (Expression2 )

Statement2 .

.

.

else if (ExpressionN )

StatementN

else

Statement N+1

Exactly 1 of these statements will be executed

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 51: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Testing Selection Control Structures

• To test a program with branches, use enough data sets to ensure that every branch is executed at least once

• This strategy is called minimum complete coverage

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 52: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Testing Often Combines Two Approaches

WHITE BOX BLACK BOX

TESTING TESTING

Code Coverage

Allows us to see the

program code while

designing the tests,

so that data values at

the boundaries, and

possibly middle values,

can be tested.

Data Coverage

Tries to test as many

allowable data values as

possible without regard

to program code.

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 53: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Testing

• Design and implement a test plan

• A test plan is a document that specifies the test cases to try, the reason for each, and the expected output

• Implement the test plan by verifying that the program outputs the predicted results

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 54: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

PHASE RESULT TESTING TECHNIQUE

Implementation Coded program Code walk-through,

Trace

Compilation Object program Compiler messages

Execution Output Implement test plan

Problem solving Algorithm Algorithm walk-through

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 55: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Chapter 6

Looping

Dale/Weems

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 56: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

While Statement

SYNTAX

while (Expression)

{ .

. // loop body

.

}

Loop body can be a single statement, a null statement, or a block

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 57: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Complexity

• Complexity is a measure of the amount of work involved in executing an algorithm relative to the size of the problem

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 58: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Chapter 9

Additional Control Structures

Dale/Weems

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 59: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Switch Statement The Switch statement is a selection control

structure for multi-way branching switch (IntegralExpression) { case Constant1 : Statement(s); // optional case Constant2 : Statement(s); // optional .

.

.

default : // optional Statement(s); // optional }

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 60: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Do-While Statement Do-While is a looping control structure in

which the loop condition is tested after each iteration of the loop

SYNTAX

do

{

Statement

} while (Expression);

Loop body statement can be a single statement or a block

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 61: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

For Loop

SYNTAX

for (initialization; test expression; update)

{

Zero or more statements to repeat

}

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 62: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Break Statement

• The Break statement can be used with Switch or any of the 3 looping structures

• It causes an immediate exit from the Switch, While, Do-While, or For statement in which it appears

• If the Break statement is inside nested structures, control exits only the innermost structure containing it

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 63: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Continue Statement

• The Continue statement is valid only within loops

• It terminates the current loop iteration, but not the entire loop

• In a For or While, Continue causes the rest of the body of the statement to be skipped; in a For statement, the update is done

• In a Do-While, the exit condition is tested, and if

true, the next loop iteration is begun

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 64: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Chapter 7

Functions

Dale/Weems

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 65: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

FunctionName( Argument List )

The argument list is a way for functions to communicate with each other by passing information

The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function

Function Call Syntax

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 66: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Prototypes

A prototype looks like a heading but must

end with a semicolon, and its parameter

list needs only to contain the type of each

parameter

int Cube(int ); // Prototype

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 67: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Function Calls

When a function is called, temporary memory is allocated for its value parameters, any local variables, and for the function’s name if the return type is not void

Flow of control then passes to the first statement in the function’s body

The called function’s statements are executed until a

return statement (with or without a return value) or the closing brace of the function body is encountered

Then control goes back to where the function was called

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 68: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Header Files

Header Files contain – Named constants like

const int INT_MAX = 32767;

– Function prototypes like float sqrt(float);

– Classes like

string, ostream, istream

– Objects like

cin, cout

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 69: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Classified by Location

Always appear in

a function call

within the calling

block

Always appear in

the function

heading, or

function

prototype

Arguments Parameters (actual parameters) (formal parameters)

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 70: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Value Parameter Reference Parameter

The value of the

argument (25)

is passed

to the function when

it is called

The memory address (4000)

of the argument

is passed

to the function when

it is called

25

4000

age

In this case, the

argument can be a

variable identifier,

constant,

or expression

In this case, the argument

must be a variable

identifier

Argument

in Calling Block

70 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 71: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Default Parameters

• Simple types, structs, and classes are value parameters by default

• Arrays are always reference parameters

• Other reference parameters are marked as such by having an ampersand(&) beside their type

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 72: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

An Assertion

An assertion is a truth-valued statement--one that is either true or false (not necessarily in C++ code)

Examples

studentCount > 0

sum is assigned && count > 0

response == ‘y’ or ‘n’

0.0 <= deptSales <= 25000.0

beta == beta @ entry * 2 Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 73: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Preconditions and Postconditions

• A precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked

• A postcondition describes the state at the moment the function finishes executing, providing the precondition is true

• The caller is responsible for ensuring the precondition, and the function code must

ensure the postcondition

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 74: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Chapter 8

Scope, Lifetime, and More on

Functions

Dale/Weems

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 75: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

75

Scope of Identifier

The scope of an identifier (or named constant) is the region of program code in which it is legal to use that identifier for any purpose

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 76: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

76

Local Scope vs. Global Scope

• The scope of an identifier that is declared inside a block (this includes function parameters) extends from the point of declaration to the end of the block

• The scope of an identifier that is declared outside of all namespaces, functions, and classes extends from point of declaration to the end of the entire file containing the program code

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 77: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

77

Detailed Scope Rules 1 Function names have global scope

2 A function parameter’s scope is identical to the scope of a local variable declared in the outermost block of the function body

3 A global variable’s (or constant’s) scope extends from its declaration to the end of the file, except as noted in rule 5

4 A local variable’s (or constant’s) scope extends from its declaration to the end of the block in which it is declared, including any nested blocks, except as noted in rule 5

5 An identifier’s scope does not include any nested block that contains a locally declared identifier with the same name (local identifiers have name precedence)

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 78: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

78

Namespace Scope

• The scope of an identifier declared in a namespace definition extends from the point of declaration to the end of the namespace body, and its scope includes the scope of a using directive specifying that namespace

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 79: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

79

– Use a qualified name consisting of the namespace, the scope resolution operator ::

and the desired the identifier

alpha = std::abs(beta);

– Write a using declaration

using std::abs;

alpha = abs(beta);

– Write a using directive locally or globally

using namespace std;

alpha = abs�(beta);

3 Ways to Use Namespace Identifiers

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 80: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

80

Automatic vs. Static Variable

• Storage for automatic variable is allocated at block entry and deallocated at block exit

• Storage for static variable remains allocated throughout execution of the entire program

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 81: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

81

Default Allocation

• Local variables are automatic

• To obtain a static local variable, you must use the reserved word static in its declaration

Tomado de: Dale, N. Weems, C. Programming and problem solving With C++. 4th. Ed. Instructor material, 2005

Page 82: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

Anexo 1:

Método de Ordenamiento Quicksort

Page 83: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 83

MÉTODO DE ORDENAMIENTO "RÁPIDO" (QUICK SORT)

• Es uno de los más eficientes de ordenamiento interno. Es un algoritmo recursivo cuya idea central es:

1. Se toma un elemento X de cualquier posición del arreglo

2. Se trata de ubicar a X en su posición correcta, esto es, que todos los elementos que se encuentren a su izquierda sean menores o iguales a X y los de su derecha mayores

3. Se repiten los pasos anteriores recursivamente, pero ahora aplicándose al sub -vector que quedo del lado derecho y al que quedó del lado izquierdo.

4. El proceso termina cuando todos los elementos están ordenados.

Page 84: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 84

MÉTODO DE ORDENAMIENTO "RÁPIDO" (QUICK SORT)(cont.)

Para ejecutar el paso 2:

• Escoge un número, le llamaremos pivote

• Empezando por el extremo derecho hacia el izquierdo y hasta donde está el pivote, encuentra a alguno que sea menor que él. Si lo hay intercambialos. Este lugar del intercambio acota ahora los recorridos.

• Empezando en el extremo izquierdo hacia el derecho, y hasta donde esta el pivote, encuentra a alguno que sea mayor que el. Si lo hay intercambialos.

• Repite hasta que el inicio y final del recorrido se "traslapen"

Page 85: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 85

MÉTODO DE ORDENAMIENTO "RÁPIDO" (QUICK SORT)(cont.) Ejemplo paso 2

Page 86: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 86

ALGORITMO DE ORDENAMIENTO RÁPIDO

• ALGORITMO QuickSort( A, N ) • // Pre: El arreglo A contiene los datos a ordenarse N es el número de elementos >=

0. Este algoritmo no considera la posición 0 de A.

• //Post: A contiene los objetos ya ordenados

• 1. UbicaElementos(1,N);

• // Fin de Quicksort.

• ALGORITMO UbicaElementos(inicio , fin) • // Pre: inicio <fin

• // Post: Desde inicio hasta fin, los elementos quedarán ubicados en su posición correcta. // // Se selecciona como pivote al elemento que inicialmente esta en A[iinicio]

• 1. izq = inicio; der = fin; pos = inicio; bandera = true;

• // Empezando por la derecha, busca algún elemento menor que pivote

Page 87: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 87

ALGORITMO DE ORDENAMIENTO

RÁPIDO (Cont.)

• 2. Mientras (bandera) {

• 2.1 bandera = false;

• 2.2 Mientras (A[pos]<= A[der] ) AND (pos <>der) {

der = der -1

}

• 2.3 Si (pos <>der) {

// Si hallo algún elemento menor que pivote del lado rerecho,

// lo intercambia con pivote, que esta en pos…

aux = A[pos];

A[pos] = A[der];

A[der] = aux;

// y actualiza desde donde continuará recorriendo

pos = der; // Ahora empezando por la izquierda busca algún elemento

// mayor que pivote

Mientras (A[pos]>= A[izq]) AND (pos <>izq) { izq = izq + 1; }

Page 88: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 88

ALGORITMO DE ORDENAMIENTO

RÁPIDO (Cont.)

• Si (pos<>izq) {

// si halló alguno, lo intercambia con pivote…

bandera = true ;

aux = A[pos];

A[pos] = A[izq];

A[izq] = aux ;

// y actualiza desde donde debe continuar

pos = izq; }

} // fin del 2.3 } // fin del 2

// A este punto el pivote esta colocado en su posición correcta (todos a su

// izquierda son menores y todos a su derecha son mayores)

// Si hay elementos del lado izquierdo del pivote, se llama recursivamente…

• 3. Si (pos - 1) > inicio UbicaElementos( inicio, pos - 1 ) ;

// Si hay elementos del lado izquierdo del pivote, se llama recursivamente…

• 4. Si fin > (pos + 1) UbicaElementos( pos + 1, fin);

// Fin de UbicaElementos.

Page 89: Coordinación de Ciencias Computacionalesccc.inaoep.mx/~pgomez/cursos/programacion/presentaciones/sema… · Libros • Libros de texto: • 1.Dale, Nell and Weems, Chip. Programming

(c) Pilar Gómez-Gil, 89

ORDEN DE COMPLEJIDAD DE QUICKSORT

• En el caso en que los números a ordenarse estén distribuidos al azar uniformemente, el número de comparaciones a realizarse es:

• lo que representa un orden O(n*log(n)) para este caso

• En el peor de los casos, que sucede cuando los números están completamente ordenados o exactamente al revés, el número de comparaciones a realizarse es:

• lo que representa un orden O(n2) para este caso.

)log()1( nn