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 2022.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
char *s1;
s1 = string_duplicate("this is a string");
...
free(s1);
Chapter 4: Data Structures & Algorithms © HDC 2022.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
/* Private interface */
/* initial vector capacity */
static const int StartSize = 1;
/* geometric growth of vector capacity */
static const float GrowthRate = 1.5;
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
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 2022.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
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]