Advanced Data Structure I-3
Advanced Data Structure I-3
In this chapter, we present basic notions about algorithms, i.e. how to write an algorithm that
solves any given problem.
I. Algorithm concept
1. Definition
A computer program allows the computer to solve a problem, but before communicating to the
computer how to solve this problem, we must first be able to solve it ourselves: that is to create
an algorithm.
Algorithmics refers to the discipline that studies algorithms and their applications in computer
science .
Problème
Algorithme Résultat
Données
The program will only be the translation of the algorithm into a programming language, that is
to say, a language simpler than French in its syntax, without ambiguities, which the machine can
use and transform to execute the actions. that he can describe. Pascal, C, Java and Visual Basic
are names of programming languages.
1
Developing an algorithm is a demanding problem-solving process
Writing an algorithm is a thought exercise that is done on paper
The algorithm is independent of the programming language, for
example, we will use the same algorithm for an implementation in Java,
or in C++ or in Visual Basic
The algorithm is the raw solution of a computer problem.
3. Representation of an algorithm
Historically, there are two ways to represent an algorithm:
The Organization Chart : graphic representation with symbols
(squares, diamonds, etc.)
Provides an overview of the algorithm
Representation almost abandoned today
Pseudo-code : textual representation with a series of conventions
resembling a programming language (this is an informal language close
to natural language and independent of any programming language).
It is more convenient to write an algorithm
Its representation is widely used
2
Once the algorithm has been established, it is now necessary to create the corresponding
program.
2. Creating a program
Solving a given problem involves a succession of steps, namely:
Syntactic errors : they are noticed during compilation and are the result of poor writing
in the programming language.
Semantic errors: they are noticed at execution and are the result of poor analysis. These
errors are much more serious because they can be triggered while the program is running.
To write a program you must choose a programming language that corresponds to it:
Choosing a programming language is not easy, each one has its specificities and corresponds
better to certain types of uses.
3
Variables, Types and Basic Instructions
I. THE VARIABLES
1. Basic Structure
In pseudo-code the general structure of an algorithm is as follows:
Algorithm algorithm_name
BEGIN
{Continuation of statements}
END .
Header part: this is the first line of the algorithm, it begins with the word algorithm
followed by a space then the name of the algorithm.
Declarations part: in this part, all objects used in solving the problem must be declared.
Processing part: this part begins with the word Start and ends with the word End. It
contains the actions used in resolving the problem.
2. Concept of variable
The data manipulated in an algorithm are called variables . A variable is used to store the value
of data in a programming language. It designates a memory location whose contents can change
during a program (hence the name variable).
Each memory location has a number that allows you to refer to it uniquely: this is the memory
address of this cell.
a. Ruler
The variable must be declared before being used, it must be characterized by:
A name (Identifier)
4
A type which indicates all the values that the variable can take (integer, real, boolean,
character, character string, etc.)
A value
b. Identifiers: rules
The choice of the name of a variable is subject to a few rules which vary depending on the
language, but in general:
A name must begin with an alphabetical letter. Example: E1 (1E is not valid)
Must consist only of letters, numbers and the underscore (“_”) (Avoid punctuation
characters and spaces). Examples: SMI2008, SMI_2008. (SMP 2008, SMP-2008,
SMP;2008: are invalid)
Must be different from the reserved words of the language (for example in C: int, float,
double, switch, case, for, main, return, …)
The length of the name must be less than the maximum size specified by the language
used (in c, the name must be at most 32 characters).
In c, upper case letters are distinguished from lower case letters: a and A are two different
nouns.
Tip: for code readability, choose meaningful names that describe the data being manipulated.
Examples: NoteStudent, Price_includes tax, Price_excl. tax.
Note: in algorithmic pseudo-code, we will respect the rules cited, even if we are free in the
syntax.
In algorithmic language there are 4 basic types of variables. We can cite: integers , real
numbers , characters and booleans .
1. The integers
They represent integers, the operations that can be used on integers are:
5
All basic elementary operations are permitted: + (addition), - (subtraction), * (product), /
(division)
The classic comparison operators: <, >, =, ...
The division / is the Euclidean (or integer) division. Ex: 11 / 4 = 2 and not 2.75!)
There is the modulo % operator, which gives the remainder of the Euclidean division. Ex:
11%4 = 3
2. The real
To represent integers, the operations that can be used on integers are:
3. The characters
This is the domain made up of alphabetic and numerical characters. A variable of this type can
only contain one and only one character. The elementary operations that can be performed are
comparisons: <, >, =, ...
4. Booleans
A logical type variable (boolean) can take two values: TRUE (1) or FALSE (0).
The most used main operations are:
Truth tables :
A B A AND B A OR B A NOT A
FAKE FAKE FAKE FAKE FAKE TRUE
FAKE TRUE FAKE TRUE TRUE FAKE
TRUE FAKE FAKE TRUE
6
TRUE VAI TRUE TRUE
Comparison operators: =, ≤, ≥, ≠
5. Variable declaration
Any variable used in a program must have been the subject of a prior declaration. In pseudo-
code, the declaration of variables is carried out in the following form:
Example :
Variables i, j, k: integer
x, y: real
OK: boolean
Declaring a variable amounts to reserving a memory location for it. We don't know its initial
value!
6. Concept of constant
A constant is a variable whose value does not change during the execution of the program; it can
be a number, a character, or a string of characters. In pseudo-code,
7
III. Basic Instructions
In what follows we describe the list of basic operations that can make up an algorithm. They are
described in pseudocode (pseudolanguage).
An algorithm is made up of four types of instructions considered as small basic building blocks:
1) Assigning variables
2) Reading and/or writing
3) The tests
4) Buckles
1. Assignment
Assignment consists of assigning a value to a variable (i.e. filling or modifying the contents of a
memory area). In pseudo-code, the assignment is denoted by the sign ← .
Examples 1 : i ←1, j ←i, k ←i+j, x ←10.3, OK ←FALSE, c1 ←'I', c2 ←c1, x ←4, x ←j (with i,
j, k: integer; x: real; ok: boolean; c1, c2: character)
Examples 2
Remarks :
The C programming language uses the equal sign = for the ← assignment.
During an assignment, the expression on the right is evaluated and the value found is
assigned to the variable on the left. So, A←B is different from B←A
8
Assignment is different from a mathematical equation:
The operations x ← x+1 and x ← x-1 have meaning in programming and are called
increment and decrement respectively.
A+1 ← 3 is not possible in programming languages and is not equivalent to A ← 2
Some languages give default values to declared variables. To avoid any problems it is
preferable to initialize the declared variables.
2. Reading
Read(variable)
This operation makes it possible to assign to a variable a value entered by means of an input
device (generally the keyboard).
Reading Examples
Note: The program stops when it encounters a Read instruction and continues only after the
expected input is entered using the keyboard and the Enter key (this key signals the end of the
input).
Advice: Before reading a variable, it is strongly recommended to write messages on the screen,
in order to warn the user of what to type.
3. Writing
Write(expression)
Writing examples
Write('hello') Displays the message hello (constant)
9
Write(a, b+2, "Message") Displays the value of a, then the value of the expression b+2 and
finally the word ''message''.
Evaluating the expression provides a single value that is the result of the operation.
Noticed :
10
You cannot add an integer and a character
However, in certain languages we can use an operator with two operands of different
types, this is for example the case with arithmetic types (4 + 5.5)
The meaning of an operator can change depending on the type of operands, e.g.
The + operator with integers performs the addition, 3+6 is 9
With character strings it performs concatenation, “hello” + “everyone” equals “hello
everyone”
6. Operator priority
For the arithmetic operators given above, the order of priority is as follows (from highest priority
to lowest priority):
(): parentheses
^: (elevation to power)
*, / (multiplication, division)
% (modulo)
+, - (addition, subtraction)
Example: 9 + 3 * 4 is 21
If necessary, parentheses are used to indicate the operations to be carried out as a priority.
Example: (9 + 3) * 4 is 48
With equal priority, the expression is evaluated from left to right
7. Boolean operators
Associativity of operators and and or . Example: a and (b and c) = (a and b) and c
Commutativity of operators and and or Example: a and b = b and a ; a or b = b or a
Distributivity of operators and and or Example: a or (b and c) = (a or b) and (a or c) ; a
and (b or c) = (a and b) or (a and c )
Involution ( homography reciprocal ): no no a = a ; Morgan's Law: not (a or b) = not a
and not b ; no (a and b) = no a or no b
Example: let a, b, c and d be any four integers:
(a<b)| |((a>=b)&&(c==d))↔ (a<b)| |(c==d) because (a<b)| |(!(a<b)) is always true
11
Conditional Statement
This chapter deals with the notions of conditions (simple, Boolean, compound conditions) then
introduces conditional structures ( If, If-Then and If-Else-If ) and defines the choice tree. The
Complements describes the selective According as well as the If- expression operator.
I. Conditions
1. Comparison operators
Also called relational operators or comparators, they generally act on numeric variables or strings
and give a Boolean result. For characters and strings, the alphabetical order determines the result.
Mathematical Algorithmic
Meaning
operators equivalent
< Strictly less than <
≤ Less or equal <=
> Strictly superior >
≥ Greater than or equal to >=
= Equality =
≠ Different or inequality <>
2. Simple condition
Denoted v1 Φ v2 , it associates a comparison operator Φ and two values v1 and v2 of the same
nature (same type or comparable types) and delivers a Boolean result:
Examples
eval(2<3) is True .
eval(6*3=13) is False .
12
eval('A'<'E') is True because the alphabetical order is respected in the ASCII codes
assigned to the letters.
eval("milou"<"tintin") is True as is eval("assembler"<="java") .
eval('a'<'A') is False because uppercase letters come before lowercase letters.
eval("Hello">"Good day") is False because the space is before the letters.
If n1 and n2 are two integer variables containing the values 7 and 5, eval(2*n1>n2+3) is
eval(2*7>5+3) i.e. eval(14>8) therefore True .
3. Compound condition
More simply condition or logical expression Noted b1 Ψ1 b2 Ψ2. . ., it associates logical
operators Ψi and Boolean values bj and delivers a Boolean result ( True or False ). It allows
simple conditions to be linked into a single “super-condition”.
Examples:
The integer a must be strictly greater than zero and strictly less than 100: a > 0 And a <
100
Color c must be Red, Green or Blue: c = Red Or c = Green Or c = Blue
Color c must not be Black: No (c = Black)
“At a crossing light, I stop if it is red or orange and if my speed is less than 40km/h. In
other cases, I pass. »: stop <- (light = red) Or (light = orange And speed < 40) pass <-
No stop
13
Lazy evaluation saves time but above all it avoids execution errors .
Example :
It is equivalent to:
(no((a+2)<30))
14
b. Example: Lazy evaluation
The table below collects the evaluations of the Boolean expression:
For example, the second column of the table shows that if A contains 0 and B contains -3, then
Boolean evaluation of expr returns True . Additionally, if the box is empty, this means that the
condition is not evaluated due to lazy evaluation.
HAS 0 11 13
B -3 16 16
A > 10 FAKE TRUE TRUE
A <= 12 TRUE FAKE
A > 10 and A <= 12 FAKE TRUE FAKE
B > 10 FAKE TRUE
no (B > 10) TRUE FAKE
expr <- (A > 10 and A <= 12) or (not (B > 10)) TRUE TRUE FAKE
The condition can be simple or complex (with parentheses and/or logical operators And, Or,
Not).
15
2. Selective If
If condition SO
| instructionsSo
Otherwise
| instructionsOtherwise
End if
The body of the “ then” clause starts after the word So and ends with the
word Otherwise . That of the “ otherwise” clause starts after the word
Otherwise and ends with the word FinSi .
This example enters a student's yearly average in an integer avg and then
displays one of two messages:
You are not moving up to the next year Bravo, you are moving up to the next
year
The first is displayed if avg < 10 , otherwise it is the second. And in the case
where 16 <= avg <= 20 , it also displays:
Algorithm pgpassage1
variable avg : real
Begin
Write("Enter average")
read(avg)
If (avg < 10) Then
write("You are not moving on to the next year")
else
write("You are moving to the next year")
If (16 <= avg And avg <= 20) Then
write("With the congratulations of the jury")
End if
End if
END
The first condition is a simple condition: avg < 10 , and the second condition
a compound condition: 16 <= avg And avg <= 20 .
16
3. Selective If-Else-If
It successively evaluates the conditionI and executes the instructionsI if it is
verified. If all n conditions fail, executes the Else instructions .
If condition1 SO
| instructions1
Else If condition 2 Then
| instructions2
Else if...
| ...
Else If conditionN SO
| instructionsN
else
| instructionsOtherwise
End if
Question How does the algorithmic language distinguish between an If - Else - If structure and
cascading If structures ?
Answer When the keywords Otherwise and If are found in succession on the same line, the
language activates the interpretation of an If - Else - If structure .
III. Supplements
1. Selective According
According structure is a simplification of writing several nested alternatives.
Two forms exist:
17
Else If expr = one of the values in listN Then
# instructions when the value is in listN
Otherwise
# instructions when the value of the variable # is not found in any of the
previous lists
End if
Selective According to (conditions)
If condition1 Then
# instructions when condition1 is true Else If condition2 Then
# instructions when condition2 is true
Otherwise If ...
Else If conditionN Then
# instructions when conditionN is true
Otherwise
# instructions to execute when none of the # preceding conditions are true
End if
According to expression
| Case list1 of values separated by commas
| | instructions1
| | ...
| Case listN of values separated by commas
18
| | instructionsN
| Case Other
| | instructionsOtherwise
EndAccording to
Note: Care must be taken not to appear the same value in several lists.
According to is less general than If:
The expression must be a discrete value (Integer or Character).
Cases must be constants (no variables).
If these rules are verified, the According is more efficient than a series of Cascading Ifs (because
the expression of the According is only evaluated once and not in each of the Ifs).
According to
| condition1
| | instructions1 (when condition1 is true)
| ...
| conditionN
| | instructionsN (when conditionN is true)
| Other
| | instructions Otherwise (none of the conditions checked)
EndAccording to
Make sure that the conditions do not <overlap> , i.e. that no two of them are
ever true simultaneously.
Algorithm PGJsem1
Variable jr: Integer
begin
| write (“Number of the day”)
19
| read (jr)
| According to jr
| | Case 1
| | | write ("Monday")
| | Case 2
| | | write ("Tuesday")
| | Case 3
| | | write (“Wednesday”)
| | Case 4
| | | write ("Thursday")
| | Case 5
| | | write ("Friday")
| | Case 0, 6
| | | write ("Weekend")
| | Case Other
| | | write ("Invalid day number")
| EndAccording to
END
5. If-expression operator
Ifi(exprBool, exprThen, exprElse)
Evaluates the logical expression exprBool and if it is verified, performs the expression exprThen,
otherwise the expression exprElse. The exprThen and exprElse must be of the same type. This
very shortened syntax should be reserved for small tests.
Loop
While <Condition> Do
Instructions …
EndWhile.
This structure allows the repetition of a sequence of operations as long as the condition is
satisfied (= TRUE). When the condition becomes false the loop is finished. The condition is a
20
logical expression. This expression must then be able to change its value (have the value FALSE)
to exit the loop and avoid the case of the “infinite loop”. The sequence is one or more operations.
For several operations, the start and end are mandatory. In the case of a single operation, the start
and end are optional.
Let's see the following example which allows us to display values from 1 to 10:
Algorithm displaysvalue
Var i: integer
Beginning
Write (“the following program displays values from 1 to 10“)
i←1;
While (i <= 10) Do
Write (i)
i←i+1
end While
END
This structure allows the repetition of one or more operations until a condition is verified (=
TRUE). To avoid the infinite loop, the condition must be able to change its value (have the value
TRUE). The sequence can contain one or more operations. In both cases, start and end are
optional.
Let's take the example to display values from 1 to 10:
Algorithm displaysvalue
Var i: integer
Beginning
Write (“the following program displays values from 1 to 10“)
i←1;
Repeat
Write (i)
i←i+1
up to (i>10)
END
21
Note: For the While and Repeat loop, we often use a variable, called an index, initialized to an
initial value before executing the loop. Inside the loop, the index will be incremented (by adding
a value to the current value), or decremented (by decreasing the current value) to reach the loop
stopping condition. In addition, we execute the repeat loop code at least once before testing the
condition.
The following table summarizes the differences between the two loops While and Repeat:
Table 3: Comparison between while and repeat loops
Instructions …
EndFor
This structure makes it possible to repeat a sequence of operations for all the values of a variable
called control variable (Counter) from an initial value to a final value. The number of
repetitions of the sequence of instructions is known in advance . After each execution of the
loop body, the control variable is increased by one unit (Increment). The default value of the
increment is equal to 1 (in case it is not specified). The control variable is of type integer. The
22
initial value and final value are constants or integer variables. These two values make it possible
to calculate the number of repetitions of the sequence:
nbr = final value - initial value + 1 (in the case where the step is equal to 1).
Notes: In a For loop, the counter (control variable) can be used, but it should never be changed
inside the loop.
algorithm Nested_loops
Var i, j: integer
Beginning
i←1
As long as (i<=10) Do
j←1
Repeat
Write (i, '*', j, '=', i*j)
j←j+1
Until (d > 10)
i←i+1
EndWhile
End .
This code can be rewritten as follows:
algorithm Nested_loops
Var i, j: integer
Beginning
23
For i from 1 to 10 Do
For d from 1 to 10 Do
Write (i, '*', j, '=', i*j)
EndFor
EndFor
End .
Chapitre 1. Arrays
The types presented so far are simple types. There are other so-called structured (complex) types.
A structured type is any type defined on the basis of other types. Starting with the type that we
consider the most important of the structured types, namely the array type.
A table has a name (Tab_Name). It is also characterized by two indices (index_min, index_max).
The type of array elements is indicated by data_type.
This example allowed us to replace the declaration of 10 variables Note1, Note2, …, Note10 of
real type with a single structure, namely the Note table.
The capacity of an array (the number of elements the array can hold) cannot be changed during
the execution of a program. The size of the table must therefore be large enough for handling. For
programming flexibility, we can use a constant as follows:
24
The two indices (index_min, index_max) must be of ordinal type (scalar or discrete),
generally integer. A type is said to be ordinal if its elements are countable, ordered with a
min value and a max value.
The two indices allow you to calculate the number of elements in the array. In the case of
integer type, nbr_elements = max_index - min_index + 1.
1. Manipulating a table
A table can be represented by a set of boxes, one next to the other, or one under the other,
schematized as follows:
1 2 3 4 5 6 7 8 9 10
An array element is accessible by its position (index) in the array. The Note array is a single-
dimensional array, where each element is accessible by a single index. For example Note[1] ←
0.25; allows you to assign the value 0.25 to the first box in the table. The Note table becomes:
1 2 3 4 5 6 7 8 9 10
0.25
The index can be expressed directly as a plaintext number. It can also be a variable or a
calculated expression. For example:
algorithm exe_tab
Var T: array [1..5] of integer
X: integer
Begin
X←3
T[1] ← 7
T[X] ← 18
T[X-1] ← 4
END.
After executing the algorithm operations, the table T is represented as
follows:
1 2 3 4 5
7 4 18
25
Remarks: For manipulating arrays, loops are frequently used.
Problem: Write the algorithm to create an array of ten integers, initialize its elements to 0, then
display them.
Solution :
algorithm init_tab
Var T: array [1..10] of integer
i: integer
Begin
For i from 1 to 10 Do
T[i] ← 0
EndFor
For i from 1 to 10 Do
Write (T[i])
EndFor
END.
2.
26
2 30.77 166 5.44 9.6 7.57 10.5 770 4.83 510 10.5
3 0.62 61 0 2.06 17.5 80.95 0.04 473 10 1.25
An array element is accessible by two indices (row and column). For example, Note[2,3]=5.44.
The most used tables are one or two dimensions, but it is possible to define tables with three or
four dimensions, or even more. For example :
Note: Array [1..10, 1..3, 'a'..'z', boolean] of real.
Note: We sometimes use the term vector to designate a one-dimensional array and the term
matrix to designate a two-dimensional array.
I. The procedures
The iterative (or repetitive or repetition) action as allows you to repeat the execution of a block of
actions 0 or more times.
1. Statement
A procedure has the following general form:
Procedure Name (lists of formal parameters with their types separated by ',')
Declaration of local variables of the procedure
Beginning
List of actions (instructions) of the procedure
END
27
2. Types and modes of passing parameters
Data parameters : they do not change value in the subroutine. Rather, their values are
used.
The results parameters : they only have meaning after the execution of the subroutine.
Rather, their values are used.
Data/results parameters : they have a value before the execution of the subroutine and
which can change after execution.
Passing by value: (given parameters) the formal parameter represents a local variable to
the subroutine and any change of parameter has no effect on the effective parameter.
When called, the values of the effective parameters are retrieved in the formal parameters
Test procedure (p1: type1, p2: type2, p3: type3, …, pn: typen) the parameters p1, p2, p3, …,
of associating with the formal parameters the address of the effective parameters. Any
Test procedure (p11: type11, p12: type12, …, p1n: type1n, var p21: type21, var p22: type22, …,
var p2n: type2n) the parameters p11, p12, …, p1n are passed by value and the parameters p21,
28
Note: Parameters passed by address are preceded by the var keyword.
c. Calling a procedure
In a main algorithm, a procedure is called in an action by specifying its name and its parameters
which become effective parameters with the respective (or real) passage mode. Thus, if a
Test procedure (p11: type11, p12: type12, …, p1n: type1n, var p21: type21, var p22: type22, …,
var p2n: type2n)
Then, at the time of the call with the real or effective parameters q11, q12, …, q1n passed by
value and the parameters q21, q22, …, q2n passed by address, the action takes the form:
Note: Formal parameters and effective parameters can have the same name.
action by specifying the name of the procedure and a value of n that becomes an effective
parameter.
Algorithm calculationSumN_prime_Integers
Var n: integer
Beginning
Write(“Give a value for n“)
Read(n)
29
Sum(n)
END
II. Functions
A function is a subroutine that renders a unique result of scalar type (integer, real, character,
boolean, string, array, etc.).
1. Statement
A function has the following general form:
Function Name(lists of formal parameters with their types separated by ','): result_type
Declaration of local variables of the function
Begin
List of actions (instructions) of the function
Function_name ←varialble_result_type
END
Note: Formal parameters of the function can only be given parameters.
2. Calling a function
As a function renders a unique result, its call is made in the main algorithm by assigning the
returned result to a variable declared in this algorithm. The call takes the following form:
Identifier ← Function_name(listOfEffectiveParameters)
Note: the types of the identified variable and the result must be compatible.
3. Example of a function
A function for calculating the sum of n prime integers.
function Sum(n: integer): integer
Var i, s: integer
Beginning
s←0
for i from 1 to n do
s←s+i
end for
sum←s
END
A main algorithm that calls this function enters a value for n and calls the function in an action
that assigns the result it returns to a variable declared in the algorithm.
Algorithm calculationSumN_prime_Integers
Var n,s: integer
30
Beginning
Write(“Give a value for n“)
Read(n)
Sum(n)
END
Recordings
This chapter presents the record data type which is used to represent, in the same variable, a finite
I. Definition
A record is a data structure used to store, in the same variable, a finite number of elements of
heterogeneous types. In memory this variable is associated with a memory space sized to a finite
number of boxes of heterogeneous dimensions that can contain its elements. A record type
II. Statement
A record type variable is declared as follows:
31
var student: person
III. Access to a field of a record
The fields of a record type variable are accessible using the variable identifier and field name.
Since the fields of a record correspond to a consecutive space of bytes, they act as variables. They
can thus be used in assignment, reading, writing, etc. actions.
Answer
ComplexSum Algorithm
Const n=10
Complex type=Registration
re: real
im: real
END
var c: array[1..N] of complex
z: complex
i: integer
beginning
z.re ← 0
z.im ← 0
for i from 1 to N do
write(“Give the real part of the complex number “, i, “: “)
read(c[i].re)
write(“Give the imaginary part of the complex number “, i, “: “)
read(c[i].im)
z.re ← z.re + c[i].re
z.im ← z.im + c[i].im
end for
write(“the sum is: “, z.re, “+ i“, z.im)
END
32
Files
I. Concept of files
A FILE (English: file) is a LOGICAL GROUPING OF DATA STORED ON A PERMANENT
MEDIUM (hard disk, for example) in order to allow subsequent reuse of the information it
contains.
a. UNstructured files
We can list in this category all files such as documents, source codes, etc.
They are made up of a text so the structure is not determined: we do not find any notion of
elementary data. The file must be taken as a whole.
These files nevertheless include a format recognized by a program which will be able to analyze
its content and find meaning in it. (.docs are read by MS Word).
b. Structured files
Unlike the first, structured files are composed of a set of elementary data that can be precisely
identified within the file.
Structure determined by elementary data markup : In this category, we will find files
of type XML, HTML, Latex, etc. Each elementary piece of data is framed by markup.
Structure organized into records : A record is a block of elementary data that describes
an entity. For example, within a “Customers” file, a record corresponds to data relating to
a customer.
A field is one of the basic data of a record: the customer number is one of the fields of a record of
the customer file (others will be for example, the company name, the address, etc.) .
33
Using a field separator character: the data is encoded in ASCII (or other character
format); a record corresponds to a line of a text file
Using a precise definition of the record and its fields using a structured type.
1,"Tim";"Burtley";"[email protected]"
2,"Max";"Ximum";"[email protected]"
Example of records of a file with a structured type:
34
a. Sequential organization
In sequential files, records are stored consecutively in the order they were entered and can only
be played back in that order.
If you need a specific record in a sequential file, you must read all the records that precede it,
starting with the first.
b. Calculated organization
In calculated placement files, records are placed at a specific position in the file. This position is
c. Indexed organization
In indexed organization files, at least 2 files are necessary for each managed file:
The key corresponds to one of the fields of the record allowing the identification of a unique
record within the file.
a. Sequential access
Sequential access involves browsing the records in a file in the order in which they are stored. To
access a recording, you must have read all the recordings that precede it.
Sequential access is carried out in only one “direction”: the records are browsed from start to
finish, with no backtracking possible.
b. Direct access
Direct access allows individual access to each of the records in a file, by accessing them directly:
35
Either with a key.
Direct access allows you to access multiple records directly, regardless of where the record is
located in the file.
4. Write to a file
WRITE_FICHIER (file, list of variables)
Data is added either from the beginning of the file or from the end (depending on opening mode).
36
5. Close a file
CLOSE(file)
6. Example program
Example program:
Record Type=Record
num: INTEGER
name: CHAIN
email: CHAIN
END
VAR f3: FILE
line: record
BEGINNING
f3 ← OPEN("file3.dat" , WRITE)
WRITE("enter number, name and email address")
READ(line.num, line.name, line.email)
WRITE_FILE(f3, line)
CLOSE(f3)
END
37
References _
Ballot, P. (2023, October 11). ALGORITHMIC INITIATION . Retrieved from Sidi Mohamed Ben
Abdellah University:
http://www.est-usmba.ac.ma/ALGORITHME/co/module_ALGORITHME_23.html
tahar, D.N. (2016). Algorithmic and programming. Mohamed Boudiaf University of Science and
Technology (Oran).
Zampieri, K., & Rivière, S. (2018). Conditional [if] structures. Unisciel, algoprog.
38
Chapter 3 Search and sorting algorithms
Structuring data is essential to manipulate it in programs. However, you must know how
to find the data in these structures, this is the goal of search and sorting algorithms.
sequential search
Sequential search: we stop when we find the element, or when we reach the end of the array.
begin
i <- 0;
if (tab[i] = e) then
39
else
i <- i + 1;
end if
endwhile
searchElement1 := find;
end;
begin
i <- 0;
nbOc <- 0;
if (tab[i] = e) then
end if
i <- i + 1;
endwhile
searchElement3 := nbOc;
end;
40
remark: there is only optimization if we find a stopping point “quickly enough”
Divide and conquer principle: we divide the data into different parts which we process separately
Example: to search for an element in an array, we cut it in two and search in each part.
- if we can run programs in parallel, it will take approximately half the time to search for the
element.
- if the array is sorted, you can only search for the element in one of the parts.
Search by dichotomy: the table is supposed to be sorted in ascending order and we are looking
for an element e in an table t
1- if it is e it is won.
Remarks :
- we cut the table into two parts not necessarily equal in size
41
Note: we find 490 in 4 iterations, a sequential search would have required 11 iterations
int i, j;
boolean find;
begin
i <- 0;
j <- tab.length-1;
if (tab[(j+i)/2] = e) then
else
j <- (j+i)/2 – 1
else
42
i <- (j+i)/2 + 1;
end if
end if
endwhile
searchElement3 := find;
end
7. Sorting an array
Problem: let it be an array of N integers arranged anyhow. We are trying to modify the table in
such a way that the integers are arranged in ascending order.
Several strategies can be used to solve the sorting problem.
Sort by selection
Bubble sort.
Insertion sort.
Quick sort (quick sort).
In what follows, we will see two strategies: selection sort, and bubble sort.
a. Sort by selection
In this case, sorting an array consists of putting element number 1, that is to say the smallest, in
the right position. Then, we put the next element in the right position. And so on, until the last
one.
Algorithm Sort_tab_by_selection
Var T: array [1..10] of integer
x, i, j: integer
Begin
For i from 1 to 10 Do
Write (“enter element in position “, i)
Read (T[i]);
EndFor
For i from 1 to 9 Do
For j from i+1 to 10 Do
If (T[i] > T[j]) Then
x ← T[i]
43
T[i] ← T[j]
T[j] ← x
end if
EndFor
EndFor
For i from 1 to 10 Do
Write (T[i])
EndFor
End .
b. Bubble sorting
The basic idea of bubble sort is to say that an array sorted in ascending order is an array in which
each element is smaller than the one that follows it.
TriBubbles algorithm
CONST size ←10
Var T: array [1.. size] of integer
x,i, j: integer
sort: boolean
Begin
sort ← false
x ← size
While (sort = false) do
sort ← true
For i from 1 to terminal-1 Do
If (T[i] > T[i+1]) Then
x ← T[i]
T[i] ← T[i+1]
T[i+1] ← x
sort ← false
End if
EndFor
terminal ← terminal -1
EndWhile
END
Test if an array is sorted in ascending order: we ensure that each box (except the last) has
smaller content than that of the next box.
44
if (tab[i] > tab[i+1]) then
b <- FALSE;
end if
endfor
testSort1← b;
END
1. Bubble sort
Bubble sort: we move up the largest element by permutation and start again until the array is
sorted.
Example: sort the following table in ascending order
Remarks :
- bubble sorting is in place. It is stable if we only permute the different elements.
- we could bring up the smallest element.
- we could stop as soon as the array is sorted
the sorting is stable, it would not be stable if we had put tab[j] >= tab[j+1]
2. Sort by selection
Sort by selection (selection sort): we go through the array to find the largest element, and once
we reach the end of the array we place this element there by permutation. Then we start again on
the rest of the table.
Selection sorting only performs one permutation to bring up the largest element at the end of the
array, so it is more efficient than bubble sorting.
Sort selection is in place and the algorithm given here is stable. It would be unstable if we
replaced the comparison tab[j] > tab[pg] with tab[j] >= tab[pg].
Selection sorting can be improved by positioning the largest and smallest element on each
journey through the array, according to the same principle as that used for boustrophedon
bubble sorting.
3. insertion sort
Sorting by insertion (insertion sort): we take two elements which we sort in the correct order,
then a 3rd which we insert in its place among the 2 others, then a 4th which we insert in its place
among the 3 others , etc.
45
procedure sortInsertion(var tab: Array [1..N] of integer);
var i, j, val:integer;
begin
for (i from 1 to tab.length-1 ) do
val <- tab[i];
j <- i;
while ((j > 0) and (tab[j-1] > val)) do
tab[j] <- tab[j-1];
j <- j-1;
endwhile
tab[j] <- val;
endfor
end
46