0% found this document useful (0 votes)
27 views121 pages

CH1 Upload-2023.03.02

Uploaded by

romeknight1023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views121 pages

CH1 Upload-2023.03.02

Uploaded by

romeknight1023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Data Structures

資料結構
Chih-Wei Lin(林志瑋)
Email:[email protected]
Electrical Engineering, College of Electrical Engineering and Computer Science
National Taiwan Ocean University
Data Structures
Basic Concepts
Chih-Wei Lin(林志瑋)
Email:[email protected]
Electrical Engineering, College of Electrical Engineering and Computer Science
National Taiwan Ocean University
Chapter 1 Basic Concepts

• Introduction

• Overview: System Life Cycle

• Algorithm Specification

• Data Abstraction

• Performance Analysis

• Performance Measurement
Introduction

• Computer is a science that studies information


representation and processing with computers.

• It has two issues:


• Information representation
• Information processing
Introduction

• Therefore, we need to use the Data Structures to


analyze questions:
• Analyze the characteristics of the objects in the problem
• The relationship between the objects
Steps in Computer
• The general process of a program that solves a real
problem:
• Description of the problem with data
• Data size
• Storing data
• Relationship between data?
• Data operation
• Program performance
• The questions listed above are basically answered by
the course of data structure.
Relationship between data and
information
• Data: refers to the original record that has not been
processed.
• Ex: The original score of the student exam.
• Information: The result of "data processing".
• Ex: The ranking and distribution of the grade of the class.
• Data Processing: It is a series of processing procedures that
convert "data" into "information" that is processed through a
"program".
• Ex: Grade processing system

7
Data

• It is objective, specific, factual record.


• For example,
• The factual information, such as name, birthday, phone and address
• The original scores of each subject of the mid-term exam
• These are unprocessed information, as shown in the
Original scores of various subjects
below.

8
Information
• The results after ”Data processing" are
information.
Comparison table - characteristics of data and Information

9
Information
• Data processing will organize, calculate and analyze
the original data, and make it become useful
information (including total score, average, and
ranking).
Student's complete transcript

10
Information
• Useful information is the data that decision makers
need to use when thinking about a certain problem
• It is subjective.
• For example:
• The class tutor (decision maker) wants to reward the
students according to their test scores after the students
have finished the mid-term exam.

11
Example

12
Example

13
Example

14
Data Structures

• "Data Structure" is a basic in computer science.


• It is a core between mathematics, computer hardware, and
computer software.
• It is the fundamental of designing a program.
• It is an important basis for designing and implementing:
• compilers, operating systems, database systems, and other system
programs and large-scale applications.
What is a Data Structure?

• "Data Structure" mainly discusses how to store data


in computer memory using an organized approach to
improve the efficiency of program execution.

• Therefore, a good Data Structure and an efficient


Algorithm will greatly improve the execution
efficiency of the program.

16
What is a Program?

• In the computer, how to obtain real-time and useful


information through computers?
• we must first write efficient and correct programs

17
What is a Program?

• Program = Data Structure + Algorithm


• Data structure: refers to the storage method of data in
memory
• Algorithm: It is how to process data efficiently

• Therefore, we can generate an efficient "program"


when we choose an appropriate "data structure"
and design the most efficient "algorithm"
18
Units of Data Structure

• Data structure contains


• List
• Recursive
• Tree
• Array
• Graph
• Stack
• Sort
• Queue
• Search

19
Name Phone number
Judy 0910235588
Example Amy
。。。
0952611999
。。。
Table 1-1 Linear table structure
• EX1: Telephone Number Inquiry System
A telephone directory, which records the names of N
individuals and their corresponding telephone numbers.
Assume that it is arranged in the following form:
(a1, b1), (a2, b2), ... (an, bn),

where ai, bi (i=1, 2…n) represent a person's name and phone


number, respectively.

This problem is a typical table problem. As shown in Table 1-


1. It is a a simple one-to-one linear relationship between data.
Example
• EX2: File system- disk directory
• There are many subdirectories and
files under the root directory of the
disk
• Each subdirectory can contain
multiple subdirectories and files,
but each subdirectory has only
one parent directory, and so on.
• This problem is a typical tree
structure problem( Figure 1-1)
• It is a one-to-many relationship
between data, which is a typical
non-linear relationship structure Figure 1-1 Tree structure
Example

• EX3: Traffic network map


• There can be multiple paths from one place to another.
• This problem is a typical network structure problem
• The relationship between data and data is many-to-many, which
is a nonlinear relationship structure.
Taipei
Tokyo
Beijing

New
Moscow York

Paris
London

Figure 1-2 Network structure


Example

• Recursive: mouse maze problem.

• Array: classroom seating arrangement.

• Stack: dishes, building blocks, books, elevator


• All have the characteristics of last-in-first-out

23

Recursive Array Stack


Example

• Queue: buy tickets


• first come first bought
• List: Train carriages.
• Tree: ball game.
Tree

Queue List 24
Example

• Graph: route map.


• Sort: score ranking.
• Search: team's schedule.
Graph

Sort Search 25
Example

• Write a program to compare the average grades of 5


students
• To compare the differences without using data
structures and algorithms

26
Analysis

• W/O data structures and algorithms


• Lack of flexibility: When the number of people changes, the program
will be more difficult to maintain..

• Ex: When the number of people is 50, the program codes in line
numbers 03 and 04 will become very complex, which makes errors..

27
Improvement
• Use "array" data structure: It is used to store grades
of classmates.
• Algorithm: using for loop

28
Comparison

• More flexibility when using data structures

29
Basic Concepts and Terminology

• Data
• A symbolic representation of objective things

• Data Element
• Basic unit
• A data element can consist of several Data Items.
Basic Concepts and Terminology

• Data Item
• The indivisible smallest unit of data
• A data description of a certain aspect of an objective thing.

• Data Object
• A collection of data elements with the same properties,
• A subset of the data.
• Such as character set C={‘A’, ‘B’, ‘C’…}
Basic Concepts and Terminology

• Data Structure
• collection of data elements that have (exist) a certain
connection (relationship) with each other.
• The interrelationships (relationships) between elements
are called logical structures.
• There are four basic types of logical structure between
data elements
Basic Concepts and Terminology

• Data Structure
• four basic types of logical structure
• Set: relationship is "belonging to the same set".
• Linear structure: one-to-one relationship
• Tree structure: One-to-many relationship.
• Graph structure or network structure: Many-to-many relationship

Figure 1-3 Four basic structure


Basic Concepts and Terminology

• Summarization
• The relationship between data elements can be a
natural relationship, or an artificially defined
relationship.
• This natural or artificially defined "relationship" is
called a logical relationship between data elements,
and the corresponding structure is called a logical
structure.
Storage of Data Structure

• The storage of data structures


• Storage of data elements
• The representation of the relationships between the
elements.

• The relationship between elements


• Sequential representation
• Non-sequential representation
Storage of Data Structure

• Two storage structures


• Sequential storage structure
• Use the relative position of data elements in memory to represent
the logical structure (relationship) between data elements

• Linked storage structure


• Add a pointer to store the address of another element in each data
element, and use the pointer to represent the logical structure
(relationship) between data elements.
Storage of Data Structure

• Example: There is a data set A={3.0, 2.3, 5.0, -8.5,


11.0},
• Two different storage structures:
• Sequential structure: the continuous addresses for storing data
elements;
• Linked structure: There is no requirement whether the addresses
of data elements are stored consecutively.
Storage of Data Structure

• Summarization
• The logical structure and physical structure of data are
inseparable.
• The design of an algorithm depends on the chosen logical
structure
• The realization of the algorithm depends on the adopted
storage structure.
Storage of Data Structure

• Summarization
• In C language
• One-dimensional array is used to represent a sequential
storage structure
• Structure type is used to represent a linked storage
structure
Three components of a data
structure
• Logical structure:
• A description of the logical relationship between data
elements
• Storage structure:
• The storage of data elements in the computer and the
representation of their logical relationships
• Called data storage structures or physical structures.
• Data operation:
• The operation to be performed on the data.
Three components of a data
structure
• Three logical structures and their storage structures
Logical Structure Physical Structure
linear List sequential storage structure

Tree Linked storage structure


Graph Composite storage structure

Figure 1-4 Logical structure and its storage structure


System life cycle

• Good programmers regard large-scale computer


programs as systems that contain many complex
interacting parts.

• As systems, these programs undergo a development


process called the system life cycle.
System life cycle

• We consider this cycle as consisting of five phases.


• Requirements feasibility Opterion and
analysis mainenance
• Analysis Requirements Validation
analysis Testing
• Design General Integration
design Testing
• Refinement and Coding detailed Unit Testing
design
• Verification coding

V-model
System life cycle

• We consider this cycle as consisting of five phases.


• Requirements
• Analysis: bottom-up vs. top-down
• Design:
• data objects: Create an abstract data type

• operations: Focus on the algorithm's specification statement


and the design strategy

V-model
System life cycle

• We consider this cycle as consisting of five phases.


• Design:
• Example: Teaching plans for universities)
• Data objects: students, courses, professors, etc.

• Operations: insert, delete, find, etc.

• Specific operations: (1) Inserting a new course into the set of


already opened courses should, (2) also include querying a
professor's lecture course.

V-model
System life cycle

• We consider this cycle as consisting of five phases.


• Refinement and Coding
• (1) select the (storage) representation of the data object

• (2) Algorithms to implement various operations

• (3) The efficiency of the algorithm depends on the representation


of the data object
System life cycle

• We consider this cycle as consisting of five phases.


• Verification
• Program Proving

• Testing

• Debugging
System life cycle

• We consider this cycle as consisting of five phases.


• Verification
• Program Proving
• The correctness proof of the program is similar to the mathematical
proof

• Using mathematical proof method:

• (1) time-consuming, (2) not suitable for large-scale programming.

• Therefore, studies choose the well-known and correct methods.


System life cycle

• We consider this cycle as consisting of five phases.


• Verification
• Testing
• Executing code on the real test dataset.
• The selected test case should cover various situations
• The most common mistakes of the novice of the programming:
• A program must be correct without syntax errors
• The problem in selecting test case: one test set is enough.
• For example: When testing the switch statement, the test data must test all
the case statements.
• The goal of testing is program correctness.
• However, the running time of the program is equally important.
System life cycle

• We consider this cycle as consisting of five phases.


• Verification
• Debugging
• Ease of debugging
• early design stage
• Decision making for coding stage selection

• If the program documentation is complete, modularization, and


the relationship between parameters and calls is clear, then the
test work will be much easier
Pointers and Dynamic Memory
Distribution
• Pointers
• Pointer types have two basic operations:
• &: take address operation

• *: reference (indirect reference) operation

• Given the following statement


• int i, *pi;
• i is an integer variable and pi is a pointer to an integer
Pointers and Dynamic Memory
Distribution
• If pi = &i;
• &i returns the address of i and assigns it to pi

• To assign a value to i, we can write


• i = 10
• or *pi = 10

Both assignment statements above store the integer value 10 in i. The * sign before pi in the
second assignment statement is a reference, and 10 is not stored in the pointer, but stored in
the storage unit pointed by the pointer pi.
Pointers and D y n a m i c M e m o r y
Distribution

• Other operations of Pointers


• Pointer values can be used to assign values to pointer
variables
• A pointer is a non-negative integer.
• Therefore, C allows pointers to perform arithmetic
operations, including addition, subtraction, multiplication,
and division.
Pointers and D y n a m i c M e m o r y
Distribution

• Other operations of Pointers


• Pointers can be used for comparison, and the returns
“greater than”, “less than”, and “equal”.
• Pointers can also be explicitly cast to integers.
Pointers and D y n a m i c M e m o r y
Distribution

• The length of the pointer variable can take different


values in different computers.
• The length of the pointer variable will also be different in
the same computer 。
• For example, a pointer variable point to char may be
longer than a pointer variable point to float
Pointers and D y n a m i c M e m o r y
Distribution
• C uses NULL (the special value) to represent a null
pointer 。
• A null pointer does not point to a variable, nor point to a
function.
• The null pointer is represented by the integer value 0
• NULL is a macro in C, and its specific implementation is
defined as the constant value 0.
• Null pointers can be used to represent a boolean "false”
in relational expressions
• Therefore, a statement that tests for a null pointer could be:
• if (pi == NULL)
• or if (!pi)
Pointers and D y n a m i c M e m o r y
Distribution

• Dynamic memory allocation (distribution)


• Why Dynamic Storage Allocation?
• When the program is running, it needs to apply for storage space to
store information

• The C language provides a mechanism to allocate storage


space when the program is running. This area is called the
system heap
Pointers and D y n a m i c M e m o r y
Distribution
• Dynamic memory allocation (distribution)
• If a new storage space is needed, we can call the function
malloc to request a piece of memory space of the required
size 。
• If there is free memory in the current system
• The malloc function returns a pointer to the starting address of this
free memory
• Otherwise, if the current system has no free memory
• The function malloc returns a pointer to NULL.
• If you no longer need this storage space, you can call the function
free to release it and return it to the system 。
Pointers and D y n a m i c M e m o r y
Distribution
• Dynamic Memory Distribution
• Procedure 1.1 allocate and release memory space
Pointers and D y n a m i c M e m o r y
Distribution

• Dynamic Memory Distribution


• If the storage space is insufficient, calling malloc will
make the application to fail
• The code given below is more reliable and can be used to
replace the corresponding code that calls malloc in
Procedure 1,1.
Pointers and D y n a m i c M e m o r y
Distribution

• Dynamic Memory Distribution


• If the storage space is insufficient, calling malloc will
make the application to fail
• or use the following equivalent code
Pointers and D y n a m i c M e m o r y
Distribution

• Dynamic Memory Distribution


• malloc often appears in the program, it is convenient to define
a macro statement
• calling malloc in the macro statement, and exit if malloc fails.
• The following is an implementation of using a macro statement:
Pointers and D y n a m i c M e m o r y
Distribution
• Dynamic Memory Distribution
• Now, we can replace the statement calling malloc in Program
1,1 with two statements.

• Question? If we insert the following line in Program 1.1 after


the printf statement, what is the value of variable pf

The original storage space is now no longer accessible. This is an example of a dangling reference. As
long as the pointer to the dynamic storage area is lost, the original storage area is lost for the program.
Pointers and D y n a m i c M e m o r y
Distribution

• Vulnerability of pointers
• In the C program, we assign the NULL value to the
pointer, if the pointer has not yet pointed to the actual
target.
• It is possible to can avoid accessing an unapplied space, or
accessing a space that we do not have permission to access. 。
Pointers and D y n a m i c M e m o r y
Distribution

• Vulnerability of pointers
• When converting pointer types, use explicit casts
• for example:
Algorithm

• Algorithms: programs for solving mathematical


problems in a finite number of steps.
• Algorithm: a method to solve a problem.

66
Algorithm Specification
•1.3.1 Introduction
• An algorithm is a finite set of instructions that
accomplishes a particular task.
• Criteria
• input: zero or more quantities that are externally supplied
• output: at least one quantity is produced
• definiteness: clear and unambiguous
• finiteness: terminate after a finite number of steps
• effectiveness: instruction is basic enough to be carried out
• A program does not have to satisfy the finiteness
criteria.
Algorithm Specification

• Representation
• A natural language
• like English or Chinese.

• A graphic
• like flowcharts.

• A computer language
• like C.
Algorithm Specification
• Examples: (To illustrate the conversion process from problem description to
algorithm formation.)

• Selection sort program sort integers with n ≥ 1

• Solution process:
• Finding the smallest from the existing unsort integers

• Placing it in the next position on the current ordered list


Algorithm's Five Principles

• Input

• Definiteness

• Finiteness

• Correctness

• Output

70
Input

• It is not necessary to have an input.


• There may be none, or there may be multiple data inputs.

• Ex: W/O input.


• Get the current time of the system.

• Ex: W/. input


• When a number is odd or even, you need to input an integer

71
Definiteness
• Each instruction must be clear, without ambiguous.
• Ex: A number is even or old
• Algorithm 1 W/O
• (1). Enter a positive integer Definiteness
• (2). Execute modulo operation and identify whether the result is 0 or not
• (3). 0 is an even number
• Point 2 does not qualify for clarity
• It must state how to calculate the ”modulo operation"
• Algorithm 2
• (1). Enter a positive integer N W/.
• (2). If N is divided by 2, the remainder is 0 Definiteness
• (3). Then N is an even number

72
Finiteness

•Definition
• Algorithms cannot have infinite loops
• They must be completed in finite steps.

• Algorithms are not really executable programs, but


real programs are actions that can have infinite
loops.
• Ex: OS
73
Correctness

• Algorithm is the method to solve the problem,


therefore, correctness is the most basic requirement.

• Ex:
• (1). Enter a positive integer N
• (2). If N is divided by 2, the remainder is 0
• (3). Then N is an odd number =>應該改為偶數 符合明確性,但不正確

74
Output
• at least one output

75
Three types of Algorithms

• Text

• Flowchart

• Pseudo Code

76
Text

• Algorithms can be described in words


• They are relatively imprecise

• Therefore, they are rarely used.

• Please use "text " to describe the process of a user logging in with the
account and password.
• Step 1: Enter user ID and password

• Step 2: Determine whether the account number and password are correct

• Step 3: If it is correct, you can log in to the system, otherwise you cannot log
in.

77
Flowchart
• Flowchart: Use graphics to express the steps to solve
the problem..
• Please use "Flowchart" to describe the process of a user
logging in with the account and password.

流程圖可以協助程式設計者設計程式.可以增加程式的可讀性 78
Pseudo Code

• Pseudo Code has the advantages of both "text" and


"flow chart."

• It mixes text with a programming language to


describe the steps and methods of solving problems.

79
Pseudo Code

• Please use "pseudo code" to describe the process of


a user logging in with the account and password.

In data structures, pseudocode is an widely used representation for


algorithms 80
Algorithm Specification
• Example 1.1 [Selection sort]:
• From those integers that are currently unsorted, find the
smallest and place it next in the sorted list.
i [0] [1] [2] [3] [4]
- 30 10 50 40 20
0 10 30 50 40 20
1 10 20 50 40 30
2 10 20 30 40 50
3 10 20 30 40 50
Algorithm
Specification
• Program 1.3 contains a
complete program which
you may run on your
computer
Algorithm Specification

Procedure 1.2 Selection Sort Algorithm

Procedure 1.3 swap function


To convert program 1.2 into real C language, two well-defined subtasks must be
implemented:
1.To find the minimum integer
2.To exchange the current minimum value with list[i]
The latter subtask can be implemented as a function (see Program 1.3) or as a macro.
Algorithm Specification

• Usage of function swap


• Assuming that a and b are both declared as int class, to
exchange the values stored in both:
• swap(&a, &b)

• The parameters passed to swap are the addresses of a and b

• Macro statement
• #define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=t)

These two implementations have their own advantages:


•The function implementation is easier to read
•The macro implementation is applicable to all variable types.
Algorithm Specification
• Example 1.2 [Binary search]:
[0] [1] [2] [3] [4] [5] [6]
8 14 26 30 43 50 52
left right middle list[middle] : searchnum
0 6 3 30 < 43
4 6 5 50 > 43
4 4 4 43 == 43
0 6 3 30 > 18
0 2 1 14 < 18
2 2 2 26 > 18
2 1 -
• Searching a sorted list
while (there are more integers to check) {
middle = (left + right) / 2;
if (searchnum < list[middle])
right = middle - 1;
else if (searchnum == list[middle])
return middle;
else left = middle + 1;
}
int binsearch (int list[], int searchnum, int left, int right){
/* search list[0] <= list[1] <= … <= list[n-1] for searchnum.
Return its position if found. Otherwise return -1 */
int middle;
while (left <= right) {
middle = (left + right)/2;
switch ( COMPARE (list[middle], searchnum)){
case -1: left = middle + 1;
break;
case 0 : return middle;
case 1 : right = middle – 1;
}
}
return -1;
}

*Program 1.6: Searching an ordered list


Algorithm Specification

• COMPARE(Param1, Param2)
• Comparison operations can be implemented with functions or
macros.
• Both implementation include three conditions: “less than”,
“equal to”, and “greater than”.

• In C language library functions:


• If the former is less than the latter, return -1

• If both are equal, return 0.

• If the former is greater than the latter, return 1


Algorithm Specification

• COMPARE(Param1, Param2)-Implementation
• Function

• Macro (#define)
Algorithm Specification

• Recursive algorithms
• Junior programmers take a function as something that is
called by another function
• It executes the code and then returns control to the calling function.
Algorithm Specification

• This perspective ignores the fact that functions can call


themselves (direct recursion).
• They may call other functions and then the calling
themselves again (indirect recursion).
• extremely powerful

• allow us to express a complex process in very clear term

• We should express a recursive algorithm when the


problem itself is defined recursively.
Algorithm Specification

• The timing of using a recursive algorithm?


• Here, we only give one criterion :
• If the formulation of the problem is the recursive
definition
• For example: Factorial, Fibonacci sequence, binomial coefficient
• Example 1.4 [binsearch]: convert to recursive program
(1) Determine the end of recursion and establish boundary conditions,
There are two cases of ending :
1.Successfully found(list[middle]=searchnum),
2.Search failed (left and right subscripts cross)
(2) Implement recursive calls
Each recursive call marks a step toward the goal of solving the problem

對應找成功的情形,程序無需改動;但
while語句應替換成等價的if語句。

Note that, the calling method is the same between recursive and non-
recursive functions.
• Example 1.4 [Permutations]:
Call Stack:

main

First, Perm ( string , 0 , 2 )

We Permutations the Perm ( string , 1 , 2 )


char *string = “abc” ;
Print The String
“bac”
“bca”
“abc”
“acb”
by call perm(string,0,2); Perm ( string , 2 , 2 )

0 is start index
2 is end index
SWAP
SWAP
SWAP((((list[1],list[2],
SWAP list[1],list[1],
list[0],list[0],
list[0],list[0],temp)
list[0],list[1],
list[1],list[1],
list[1],list[2], temp)
temp)
temp)
SWAP
SWAP
SWAP‘b’
SWAP
SWAP ‘a’
‘b’
‘a’ ó
‘a’óó ‘b’
‘c’
ó‘b’‘a’
‘c’
‘a’

I=0 J=3
I=1 J=0 N=2
J=1
J=2 Call
Call :: perm
perm (( list,2,
list,1,
list,1, 2)
2)
lv0 perm: i=0, n=2 abc
lv0 SWAP: i=0, j=0 abc
lv1 perm: i=1, n=2 abc
lv1 SWAP: i=1, j=1 abc
lv2 perm: i=2, n=2 abc
• Example 1.4 [Permutations]: print: abc
lv1 SWAP: i=1, j=1 abc
lv1 SWAP: i=1, j=2 abc
lv2 perm: i=2, n=2 acb
print: acb
lv1 SWAP: i=1, j=2 acb
lv0 SWAP: i=0, j=0 abc
lv0 SWAP: i=0, j=1 abc
lv1 perm: i=1, n=2 bac
lv1 SWAP: i=1, j=1 bac
lv2 perm: i=2, n=2 bac
print: bac
lv1 SWAP: i=1, j=1 bac
lv1 SWAP: i=1, j=2 bac
lv2 perm: i=2, n=2 bca
print: bca
lv1 SWAP: i=1, j=2 bca
lv0 SWAP: i=0, j=1 bac
lv0 SWAP: i=0, j=2 abc
lv1 perm: i=1, n=2 cba
lv1 SWAP: i=1, j=1 cba
lv2 perm: i=2, n=2 cba
print: cba
lv1 SWAP: i=1, j=1 cba
lv1 SWAP: i=1, j=2 cba
lv2 perm: i=2, n=2 cab
print: cab
lv1 SWAP: i=1, j=2 cab
lv0 SWAP: i=0, j=2 cba
Data Abstraction

• Data Type
definition
A data type is a collection of objects and a set of
operations that act on those objects.
• For example, the data type int consists of the objects {0,
+1, -1, +2, -2, …, INT_MAX, INT_MIN} and the
operations +, -, *, /, and %.

INT_MAX and INT_MIN are the largest and smallest integers that the
machine can represent (these two values are defined in the header file
limists.h of the C language)
Data Abstraction

• The data types of C


• The basic data types: char, int, float and double
• The group data types: array and struct
• list[5] defines an array of 5 (identical)
• array: integers with subscripts ranging from
0...4.
• A structure can be a collection of
• struct: different element types, and these
different element types must be given
explicitly.

• The pointer data type


• The user-defined types
Data Abstraction

• Abstract Data Type


Definition
An abstract data type(ADT) is a data type that is organized in
such a way that the specification of the objects and the
operations on the objects is separated from the representation
of the objects and the implementation of the operations.
• We know what is does, but not necessarily how it will do
it.
Data Abstraction

• Specification vs. Implementation


• An ADT is implementation independent
• Operation specification
• function name
• the types of arguments
• the type of the results
• The functions of a data type can be classify into several
categories:
• creator / constructor
• transformers
• observers / reporters
Data Abstraction
• Example 1.5 [Abstract data type Natural_Number]

::= is defined as
Concept of Programming

• There are five steps to programming:


• Step 1: Analyzing the problem (Requirement)
• Step 2: Designing the steps to solve the problem (Algorithm)
• Step 3: Writing the program (Coding)
• Step 4: Testing on the machine to detect errors (debugging)
• Step 5: Writing the program manual (executable)

100
Step 1: Analyzing the problem
(Requirement)
• First, you need to understand the requirements and
conditions of the problem.

• Determine the input data.

• Determines the information for output.

101
Step 2: Designing the steps to solve
the problem (Algorithm)
• Text

• Flowchart

• Pseudocode

102
Step 3: Writing the program
(Coding)
• Choose an appropriate programming language and
then write a program according to the steps of the
algorithm.

103
Step 4: Testing on the machine to
detect errors (debugging)
• A useful and easy-to-use program must go through
multiple tests.

• If there is an error, it must be corrected immediately


until it is correct.

104
Step 5: Writing the program
manual (executable)
• Users will be willing to use a powerful and complete
program

• Therefore, there must be an instruction manual for


others to use or maintain.

105
Difference Between Algorithms and
Programs
• Algorithms’ subjects are "human”
• That is, codes that can be read by anyone.
• Therefore, readability is the most
important issue.

• Program’s subjects is "computer”


• That is, it emphasizes the correctness,
maintainability and execution efficiency
of program execution results.
106
Why programming?

• Goal: Quickly solve "complex problems".


• Calculate the sum of integers from 1 to 10.
• Calculate the sum of integers from 1 to 5000.

107
Conditions for a good program

• Correctness

• Performance

• Maintainable

108
Correctness
• Correctness is the basic requirement of a good
program
• Ex: Design a program to identify parity

• The wrong result was produced because the program was


incorrect.

109
Performance
• Performance refers to the time it takes for the program to
actually execute.
• Generally, the evaluation of execution time is to calculate the
total number of times that execute the code which refers to
frequency.
• The higher the frequency, the longer the required execution time
• Ex: Calculate the number of executing times of the variable Count in
the following program ?

110
Maintainable

• A good program not only needs to be efficient and


correct but also the readability
• This is the issue of programming methodology and style.

• Ex:
• Modularization
• Annotation

111
Tips of Maintainable

• Layout

• Annotation

• Name

112
Layout
• W/. Indentation

• W/O Indentation

113
Annotation
• It is a non-executable statement
• That is, it is read by humans, and the computer will not
execute it.
• Annotation explains the function and goal of a
specific statement in code.
• ”//”: It can be written at the end of the code or as a single
line comment.

• ”/*…..*/”: When the content of the comment exceeds one


line.

114
Naming variables and function
names
• Good Declaration
• The variable name can express the meaning of the variable
• Ex: string stud_name;

• Bad Declaration
• It is impossible to know the meaning of the variable
immediately (Thinking).
• Ex: string A, B;

115
Structured Programming
• Use the "top-down" technique to decompose the
program into modules with independent functions,
as shown in the figure below.

結構化程式設計示意圖
116
Structured Programming
• Each independent functional module is composed of
three basic structures of structured programming.
請分別撰寫一個程式

117
Sequential Structure
• The program is executed one by one in order from
top to bottom.

118
Selection Structure
• The paths are selected to execute based on the
conditions.
• Ex: Calculate the average score of two subjects, and
judge whether the average score is passed.

119
Repetition Structure
• It refers to the statement that a program is repeatedly
executed multiple times.
• Use the loop to calculate the average score of the two
subjects.

120
Efficiency Evaluation of
Algorithms
• It is used to calculate the time required for the actual
execution of a program after compilation.

121

You might also like