Chapter4_Data_Structures_and_Algorithms
Chapter4_Data_Structures_and_Algorithms
Embedded Programmings
Chapter 4: Data
Structures & Algorithms
Lecturer: Dr. Hoang Duc Chinh (Hoàng Đức Chính)
Department of Industrial Automation
School of Electrical Engineering
Email: [email protected] ©HDC 2021.1
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
char buffer[SIZE];
Student student_list[100];
Size of array must be known before compiling, users cannot
enter the number of elements, in another way, this number
cannot be a variable less flexible
Occupy a fixed slot in stack (if it is a local variable) or data
segment (if it is a global variable) inefficient and inflexible
use of memory
char *s1;
s1 = string_duplicate("this is a string");
...
free(s1);
Chapter 4: Data Structures & Algorithms © HDC 2021.1 22
Common errors
The pointer points to an undefined value
“memory corruption”
The pointer points to NULL
Program halts
Free a pointer pointing to a memory block which is not
dynamic memory like stack, constant data
Not free memory after using (memory leak).
Access elements which are not in the range of the
allocated array
/* Allocate rows. */ cấp phát bộ nhớ động cho từng hàng của ma trận
for (i = 0; i < m; ++i)
p[i] = (double *) malloc(n * sizeof(double));
return p; m x 1 dim array dùng con trỏ **p trỏ đến
mỗi con trỏ của mảng p quản lý mảng 1 chiều này
}
}
for (i = 0; i < m; ++i, q += n)loop để gán từng con trỏ trong mảng p cho từng đc
trong mảng a sao cho mỗi p[i] trỏ đến 1 hàng của ma
p[i] = q; trận q được tăng lên n sau mỗi vòng lặp để trỏ đến hàn
return p; tiếp theo
}
Chapter 4: Data Structures & Algorithms © HDC 2021.1 29
Example: Matrix (cont.)
void destroy_matrix(double **p)
/* Destroy a matrix. Notice, due to the
method by which this matrix was created,
the size of the matrix is not required.*/
{
free(p[0]);
free(p);
}
/* Private interface */
/* initial vector capacity */
static const int StartSize = 1;
/* geometric growth of vector capacity */
static const float GrowthRate = 1.5;
Data structure:
struct Vector {
double *data; con trỏ đến mảng lưu trữ các phần tử
};
Declaration of its basic functions:
Vector createVector(int n, double init);
void destroyVector(Vector);
double getElem(Vector, int i);
void putElem(Vector, int i, double d);
Vector addVector(Vector, Vector);
Vector subVector(Vector, Vector);
double scalarProd(Vector, Vector);
...
#endif // VECTOR_H
b = createVector(10,2.0);
c = addVector(a,b);
//...
destroyVector(a);
destroyVector(b);
destroyVector(c);
}
Chapter 4: Data Structures & Algorithms © HDC 2021.1 48
4.4 List structure
Problem: create a structure to manage dynamic data
efficiently and flexibly, e.g.:
Email
Todo list
Graphical objects in a figure
Dynamic blocks in a simulation model (similar to SIMULINK)
Requirements:
The number of records/elements in the list changes frequently
Add or delete data operations should be fast and simple
Minimize memory usage
Item A Data A
Item B Data B
Item C Data C
Item X Data X
Data A Data B
Data B Data T
Data C Data C
Data X Data X
pHead pHead
Data A Data A
Data B Data B
Data C Data C
Data X Data X
#include <string>
using namespace std;
struct MessageItem { đầu tiên cần 1 struct 2 phần chính của email
string subject;
string content;
MessageItem* pNext; con trỏ linked list trỏ đến tin nhắn tiếp theo trong danh sách
};
struct MessageList { struct messagelist
MessageItem* pHead;trỏ đến tin nhắn đầu tiên trong danh sách
}; khi khởi tạo tin nhắn'l' con trỏ pHead trỏ đến
void initMessageList(MessageList& l);nullptr tức là danh sách ban đầu rỗng
void addMessage(MessageList&, const string& sj,
const string& ct);
bool removeMessageBySubject(MessageList&l,
const string& sj);
void removeAllMessages(MessageList&);
Advantages:
A DLL can be traversed in both forward and backward direction
The delete operation in DLL is more efficient
We can quickly insert a new node before a given node
Basic Operations
Initializing, using it and then de-initializing the stack
Two primary operations:
push() − Pushing (storing) an element on the stack
pop() − Removing (accessing) an element from the stack
Chapter 4: Data Structures & Algorithms © HDC 2021.1 67
Stack
typedef struct Stack {
double buffer[MAXSIZE]; /* Stack buffer. */
int count; /* Number of elements in stack. */
} Stack;
1 2 3
6 7 8 9 3 4 5
6 7 8 9 A B 5
struct Dictionary t {
/* table is an array of pointers to entries */
struct Nlist *table[HASHSIZE];
};
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 © HDC 2021.1 125
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 © HDC 2021.1 134
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 © HDC 2021.1 135
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.: