Chapter4_Data_Structures_and_Algorithms_part2
Chapter4_Data_Structures_and_Algorithms_part2
Embedded Programmings
Chapter 4: Data
Structures & Algorithms
© DIA 2020.2
Content
4.1. Introduction of data structures
4.2. Arrays and dynamic memory management
4.3. Vector structure
4.4. List structure
4.5. Sorting algorithms
4.6. Recursion
4.7. Bitwise operation
4.8. Event-driven programming
Desired output:
Data has been sorted in certain order
0 n-1
a Sorted array: a[0]<=a[1]<=…<=a[n-1]
double score;
} student_record; typedef struct {
double x, y ;
} point;
x
y
pentagon[1] – structure
x
y
x
y pentagon[4].x – a real number
x
y
x
y
typedef struct {
char name[MAX_NAME + 1];
int id;
double score;
} StudentRecord;
typedef struct {
char name[MAX_NAME + 1];
int id;
double score;
} StudentRecord;
Returning value is
A negative number if str1 < str2
Zero if str1 = str2
A positive number if str1 > str2
Questions:
How recursion works?
• To be discussed
Why do we need recursive functions?
• We will see the motivations
Chapter 4: Data Structures & Algorithms © DIA 2020.2 126
4.6.1 Factorial function
Function name
Parameter/
int factorial(int n) Argument
{
int product, i;
product = 1; Local variables
Type and for (i = n; i > 1; i = i - 1)
returning {
value product = product * i; 0! = 1
} 1! = 1
2! = 1 * 2
return (product);
3! = 1 * 2 * 3
} ...
1
2
3
A B C
Chapter 4: Data Structures & Algorithms © DIA 2020.2 135
Towers of Hanoi
Following is an animated representation of solving a Tower
of Hanoi puzzle with three disks.
Tower of Hanoi puzzle with n disks can be solved in
minimum 2n−1 steps. This presentation shows that a puzzle
with 3 disks has taken 23 - 1 = 7 steps.
Assume that we have 64 disks, if time taken to move 1 disk
is t [seconds]
Total required time is:
Let :
1 1
2 2 1
13 31 2
A B C
Chapter 4: Data Structures & Algorithms © DIA 2020.2 136
Towers of Hanoi
40 20 10 80 100 50 7 30 60
40 20 10 80 60 50 7 30 100
7 20 10 30 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
7 20 10 30 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
7 20 10 30 7 20 10 7 10 20
pivot_index = 0 2 4 10 12 13 50 57 63 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
0
1
2
3
4
5
6
7
8
9 F
0 1 2 3 4 5 6 7
is_path(maze, 7, 8)
0
1
2
3
4
5
6
7
8
9 F
0 1 2 3 4 5 6 7
is_path(maze, 7, 8)
0
1
2
3
4
is_path(maze, 7, 8) 5
6
7
8
9 F
0 1 2 3 4 5 6 7
E.g.: