Data Structures Chapter 1 Programming Principles Andreas Savva.
-
Upload
freddy-chopin -
Category
Documents
-
view
231 -
download
3
Transcript of Data Structures Chapter 1 Programming Principles Andreas Savva.
Data StructuresData Structures
Chapter 1Chapter 1Programming PrinciplesProgramming Principles
Andreas Savva
33
Data TypeData Type
Consists of two parts:Consists of two parts: Set of valuesSet of values Set of operations that act on the valuesSet of operations that act on the values
Example : Integer data typeExample : Integer data type Values - whole numbers in some defined Values - whole numbers in some defined
rangerange Operations - add, subtract, multiply, divide, Operations - add, subtract, multiply, divide,
etc. etc.
44
Data StructureData Structure
Consists of two parts:Consists of two parts: Collection of elements each of which is Collection of elements each of which is
either a either a data typedata type or another data or another data structure.structure.
A set of associations or relationships A set of associations or relationships ((structurestructure) involving the collection of ) involving the collection of elements.elements.
55
Examples – Data StructureExamples – Data Structure ArrayArray
Sequence of elements (data types) Sequence of elements (data types) Position association among the elementsPosition association among the elements
RecordRecord Collection of data into a single structureCollection of data into a single structure No associationNo association
44 88 1212 2020 3232 4747 6060
pos pos 00 11 22 33 44 55 66
Surname:Surname: EastwoodEastwood
Name:Name: ClintClint
Nationality:Nationality: USAUSA
Telephone:Telephone: +15678900+15678900
Age:Age: 7575
66
Classification - Data Classification - Data StructuresStructures
Linear StructureLinear Structure
Hierarchical Hierarchical (Tree) structure(Tree) structure
Graph structureGraph structure
Set structureSet structure
Unique predecessorUnique predecessor Unique successorUnique successor
Unique predecessorUnique predecessor Many successorsMany successors
Many predecessorsMany predecessors Many successorsMany successors
No predecessorNo predecessor No successorNo successor
77
ExamplesExamples
Linear StructureLinear Structure
Hierarchical Hierarchical (Tree) structure(Tree) structure
Graph structureGraph structure
Set structureSet structure
StackStack QueueQueue
Family TreeFamily Tree Computer DirectoriesComputer Directories
Computer NetworkComputer Network London UndergroundLondon Underground
You - You - Students in this Students in this classclass
88
Why do we need data Why do we need data structures?structures?
Example – Towns Data StructureExample – Towns Data Structure
You need to visit all houses in two towns once only.You need to visit all houses in two towns once only. In each town you start and finish at house number In each town you start and finish at house number
1.1. All roads are the same length.All roads are the same length. Same number of houses in each town.Same number of houses in each town.
99
1 2 3
4
567
8
Town 2Town 1
1 23
4
56
7
8
In town 1 you walk twice as far as in town 2.
Why?Because the structures are different.
1010
Choosing a data structureChoosing a data structure
The process involves:The process involves:
analyzinganalyzing the problem, the problem,
determiningdetermining basic operations basic operations
needed,needed,
selectingselecting the data structure. the data structure.
1111
Choosing the right data Choosing the right data structurestructure
The The rightright data structure will make data structure will make your operations your operations simplesimple and and efficientefficient..
The The wrongwrong data structure will make data structure will make your operations your operations complexcomplex and and inefficientinefficient..
1212
Abstract Data Types (ADT)Abstract Data Types (ADT) A module A module ((objectobject)) containing: containing:
the data structure,the data structure, the associated operations the associated operations
(subprograms).(subprograms).
Details of the module are Details of the module are hiddenhidden from the user from the user ((encapsulationencapsulation).).
This is called This is called data abstraction.data abstraction.
Modules are stored as Modules are stored as UnitUnit in Pascal,in Pascal, ClassClass in C++ and Javain C++ and Java
1313
Abstract Data Types (ADT)Abstract Data Types (ADT)
Data cannot be accessed directly.Data cannot be accessed directly. Data can only be accessed indirectly Data can only be accessed indirectly
via the subprograms (via the subprograms (methodsmethods) ) associated with the data.associated with the data.
Thus, the module contains:Thus, the module contains:The The data structuredata structure..Subprograms to Subprograms to accessaccess and/or and/or modifymodify the the data structure.data structure.
1414
C++ Classes, Objects, and MethodsC++ Classes, Objects, and Methods
A A classclass collects data and the methods used collects data and the methods used to access or change the data.to access or change the data.
Such a collection of data and methods is Such a collection of data and methods is called an called an objectobject belonging to the given class. belonging to the given class.
Every class consists of Every class consists of membersmembers that that represent either variables (called represent either variables (called data data membersmembers) or functions (called ) or functions (called methodsmethods or or member functionsmember functions). The member functions ). The member functions of a class are normally used to access or of a class are normally used to access or alter the data members.alter the data members.
ClientsClients (user programs) can declare and (user programs) can declare and manipulate objects of that class.manipulate objects of that class.
1515
Information HidingInformation Hiding A client does not need to know how the A client does not need to know how the
data are actually stored or how the data are actually stored or how the methods are programmed. This important methods are programmed. This important programming strategy is called programming strategy is called information information hidinghiding..
Data members and methods available to a Data members and methods available to a client are called client are called publicpublic..
PrivatePrivate variables and functions may be variables and functions may be used in the implementation of the class, but used in the implementation of the class, but are not available to a client.are not available to a client.
MethodsMethods of a class are public of a class are publicFunctionsFunctions in a class are private in a class are private
1616
ComparisonComparison Abstract Data TypesAbstract Data Types
High level descriptionHigh level description – logical picture of the data, – logical picture of the data, and operations that manipulate the data.and operations that manipulate the data.
Implementation of program is Implementation of program is independentindependent to the to the data structure.data structure.
Implementation of program is concerned with Implementation of program is concerned with whatwhat it can do. it can do.
NOT Abstract Data TypesNOT Abstract Data Types Concrete descriptionConcrete description – collection of data types & – collection of data types &
operations that store and retrieve individual operations that store and retrieve individual elements.elements.
Implementation of program is Implementation of program is dependant dependant to the to the data structure.data structure.
Implementation of program is concerned with Implementation of program is concerned with howhow a task is done. a task is done.
1717
Example – Abstract Data Example – Abstract Data TypeType
Main activities for operating a car are:Main activities for operating a car are: steering, accelerating, brakingsteering, accelerating, braking
The design of a car can be viewed as an The design of a car can be viewed as an ADT with operations: ADT with operations: steer, accelerate, brakesteer, accelerate, brake
Two cars may implement these operations Two cars may implement these operations in different ways.in different ways.
Most drivers can operate any car since the Most drivers can operate any car since the ADT presents a uniform method of ADT presents a uniform method of operation.operation.
1818
ProgrammingProgramming
Assumption:Assumption: You can You can designdesign and and writewrite programs. programs.
This Course:This Course: Uses C++ as a tool.Uses C++ as a tool. Will Will notnot teach you how to program. teach you how to program.
1919
Programming PrinciplesProgramming Principles
We must learn to observe important principles of We must learn to observe important principles of program design.program design.
We usually ignore them when we write small We usually ignore them when we write small programs.programs.
BUT ignoring them when writing large projects could BUT ignoring them when writing large projects could be be disastrousdisastrous..
2020
Problems of large programsProblems of large programs More difficult to More difficult to maintainmaintain them than to write them than to write
them.them.
In time there will be new requests on the In time there will be new requests on the program, and if it is not well-designed or if the program, and if it is not well-designed or if the data is not well structured it will be impossible data is not well structured it will be impossible to restructure it and the program will become to restructure it and the program will become unusable. unusable. It will cost less to write another program from scratch It will cost less to write another program from scratch
than maintaining the existing one.than maintaining the existing one.
The approachThe approach
““First make your program work and then make it prettyFirst make your program work and then make it pretty””
may be effective for small programs but not for may be effective for small programs but not for large ones.large ones.
2121
Program DesignProgram Design Divide the problem into smaller problems until Divide the problem into smaller problems until
they become of manageable size.they become of manageable size.
Project
Sub-problem
DataStructure
Commonand
compatible
Each part of a program must be well organized, Each part of a program must be well organized, clearly written or else its structure will have been clearly written or else its structure will have been forgotten at some time later or will not be forgotten at some time later or will not be understood by other programmers.understood by other programmers.
You must form good programming habits from the beginning.You must form good programming habits from the beginning.
2222
Choice of Data StructuresChoice of Data Structures The most important aspect in algorithm design is The most important aspect in algorithm design is
the way in which the data of the program is stored:the way in which the data of the program is stored: How they are arranged in relation to each other.How they are arranged in relation to each other. Which data are kept in memory.Which data are kept in memory. Which are calculated when needed.Which are calculated when needed. Which are kept in files, and how this files are arranged.Which are kept in files, and how this files are arranged.
Program TestingProgram Testing The difficulty of debugging a program increases much The difficulty of debugging a program increases much
faster than its size. faster than its size. A program twice the size of another will A program twice the size of another will likely to not take twice as long to debug, but most probably, likely to not take twice as long to debug, but most probably, four times as long.four times as long.
Many large programs (such as operating systems) are put Many large programs (such as operating systems) are put into use still containing errors that the programmers have into use still containing errors that the programmers have not spotted.not spotted.
Sometimes projects that have consumed years of effort Sometimes projects that have consumed years of effort must be discarded because it is impossible to discover why must be discarded because it is impossible to discover why they will not work.they will not work.
2323
Program CorrectnessProgram Correctness If we do not wish such a fate to our projects, then If we do not wish such a fate to our projects, then
we must use methods that:we must use methods that: Reduce the number of errors, making it easier to spot Reduce the number of errors, making it easier to spot
those that remain.those that remain. Enable us to verify in advance that our algorithms are Enable us to verify in advance that our algorithms are
correct.correct. Provide us with ways to test our programs so that we can Provide us with ways to test our programs so that we can
be reasonably confident that they will not misbehave.be reasonably confident that they will not misbehave.
MaintenanceMaintenance Since new demands will arise in the future it is Since new demands will arise in the future it is
important that a large project is written to make important that a large project is written to make it as easy as possible to be understood and it as easy as possible to be understood and modified.modified.
2424
Case StudyCase Study
The Game of LifeThe Game of Life Introduced by the British mathematician Introduced by the British mathematician
J.H. Conway in 1970.J.H. Conway in 1970. It is a simulation, not a game with It is a simulation, not a game with
players.players.
2525
Rules for the Game of LifeRules for the Game of Life It takes place on an unbounded rectangular grid in which each It takes place on an unbounded rectangular grid in which each
cell can either be occupied by an organism or not. Occupied cell can either be occupied by an organism or not. Occupied cells are called cells are called alivealive; unoccupied cells are called ; unoccupied cells are called deaddead. Which . Which cells are alive changes from generation to generation according cells are alive changes from generation to generation according to the number of neighboring cells that are alive, as follows:to the number of neighboring cells that are alive, as follows:
The neighbors of a given cell are the eight cells that touch it The neighbors of a given cell are the eight cells that touch it vertically, horizontally, or diagonally.vertically, horizontally, or diagonally.
If a cell is alive but either has no neighboring cells alive or If a cell is alive but either has no neighboring cells alive or only one alive, then in the next generation the cells dies of only one alive, then in the next generation the cells dies of loneliness.loneliness.
If a cell is alive and has four or more neighboring cells also If a cell is alive and has four or more neighboring cells also alive, then in the next generation the cell dies of alive, then in the next generation the cell dies of overcrowding.overcrowding.
A living cell with either two or three living neighbors A living cell with either two or three living neighbors remains alive in the next generation.remains alive in the next generation.
If a cell is dead, then it will become alive if it has exactly If a cell is dead, then it will become alive if it has exactly three neighboring cells that are alive. All other dead cells three neighboring cells that are alive. All other dead cells remain dead in the next generation.remain dead in the next generation.
All births and deaths take place at exactly the same time.All births and deaths take place at exactly the same time.
2626
ConfigurationConfiguration
Example 1Example 1
* *
Living neighborsLiving neighbors
0 0 0 0 0 0
0 1 2 2 1 0
0 1 1 * 1 * 1 0
0 1 2 2 1 0
0 0 0 0 0 0
By rule 2 both the living cells will die in the next generationand rule 5 shows that no cells will become alive, so thatconfiguration dies out.
2727
Example 2Example 2
0 0 0 0 0 0
0 1 2 2 1 0
0 2 3 * 3 * 2 0
0 2 3 * 3 * 2 0
0 1 2 2 1 0
0 0 0 0 0 0
Each of the living cells has a neighbor count of three, andhence remain alive, but the dead cells all have neighborcounts of two or less, and none of them becomes alive.Thus all new configurations will be identical to this one.
2828
Working ExampleWorking Example
**
** **
** **
** **
**
** **
** **
** **
** **
** **
** **
** ** **
** ** ** **
** ** **
** **
2929
Another ExampleAnother Example
**
**
**** ** **
The two configuration continue to alternate from generationto generation.
3030
The AlgorithmThe Algorithm
Set up an initial Life configuration.Set up an initial Life configuration. Print the Life configuration.Print the Life configuration. While the user wants to see further While the user wants to see further
configurations:configurations: Update the configuration by applying the rules of Update the configuration by applying the rules of
the Life game.the Life game. Print the current configuration.Print the current configuration.
3131
The Class LifeThe Class Life
enum status {dead,alive};class Life {public: void initialize(); void print() const; void update();private: int neighbor_count(int, int) const; status grid[maxrow][maxcol];
};
3232
The Main ProgramThe Main Programint main(){
Life configuration;
welcome();configuration.initialize();configuration.print();cout << "Continue viewing new generations?" << endl;while (user_says_yes())
{configuration.update();configuration.print();
cout << "Continue viewing new generations?" << endl;}
return 0;}
3333
InitializeInitializevoid Life::initialize(){ int row,col;
for (row=0;row<maxrow;row++) for (col=0;col<maxcol;col++) grid[row][col] = dead;
cout << "Enter row and column of living cells and finish with -1 -1" << endl; while ((row!=-1) || (col!=-1)) { cin >> row >> col; if (row==-1 && col==-1) cout << "Done" << endl; else if ((row<0) || (row>=maxrow)) cout << "Row out of range" <<
endl; else if ((col<0) || (col>=maxcol)) cout << "Column out of range" <<
endl; else grid[row][col] = alive;
}}
3737
User ReplyUser Replybool user_says_yes(){ char c; bool initial_response = true;
do { if (initial_response) cout << "(y/n)?"; else cout << "Respond with either y or n: "; initial_response = false;
do { cin >> c; } while (c=='\n' || c==' ' || c=='\t'); } while (c!='y' && c!='Y' && c!='n' && c!
='N');
return (c=='y' || c=='Y');}
3838
Programming GuidelinesProgramming Guidelines
Choose meaningful names.Choose meaningful names. Use common prefixes or suffixes to associate Use common prefixes or suffixes to associate
names of the same general category, i.e.names of the same general category, i.e.input_file out_file total_fileinput_file out_file total_file
Be careful with the use of the letters “I” and Be careful with the use of the letters “I” and “O”, i.e.“O”, i.e.
I = 1; x = 1; x = I; x = O; x = 0;I = 1; x = 1; x = I; x = O; x = 0; Avoid global variables when possible.Avoid global variables when possible. Avoid side-effects (changing the values of Avoid side-effects (changing the values of
global variables).global variables). Keep the functions short – less than a page.Keep the functions short – less than a page.
3939
Documentation GuidelinesDocumentation Guidelines The reading time for programs is much more than The reading time for programs is much more than
the writing time. “the writing time. “Make your program readableMake your program readable”.”. Place a prologue at the beginning of your program.Place a prologue at the beginning of your program. When each variable, constant, or type is declared explain When each variable, constant, or type is declared explain
what it is and how it is used. Better still, make this what it is and how it is used. Better still, make this information evident from the name.information evident from the name.
Introduce each significant part of your program (paragraph Introduce each significant part of your program (paragraph or function) and indicate where it ends if it is not obvious.or function) and indicate where it ends if it is not obvious.
Avoid comments that parrot what the code does, i.e.Avoid comments that parrot what the code does, i.e.count++ count++ // Increase counter by 1// Increase counter by 1
The code itself should explain The code itself should explain howhow the program works. The the program works. The documentation should explain documentation should explain whywhy it works and it works and whatwhat it it does.does.
Modify the comments along with the code.Modify the comments along with the code. Add pre-conditions and post-conditions to your functions.Add pre-conditions and post-conditions to your functions.
4040
Programming QuestionsProgramming Questions
Does the program solve the problem that is requested?Does the program solve the problem that is requested? Does the program work correctly under all conditions?Does the program work correctly under all conditions? Does the program have a good user interface?Does the program have a good user interface? Is the program logically and clearly written?Is the program logically and clearly written? Is the program well documented?Is the program well documented? Does the program make efficient use of Does the program make efficient use of timetime and and spacespace?? Does the program run on the right hardware?Does the program run on the right hardware? Can the program handle the maximum size of input?Can the program handle the maximum size of input?