0% found this document useful (0 votes)
15 views67 pages

CH2-1 - Upload-2023 03 16

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)
15 views67 pages

CH2-1 - Upload-2023 03 16

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/ 67

Data Structures

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

• Definition of Array

• The array as an Abstract Data Type

• Structures and Unions

• The polynomial Abstract Data Type

• The Sparse Matrix Abstract Data Type

• The Representation of Multidimensional Arrays


Arrays

• a set of pairs,

• A 1D array corresponds to one subscript value, a 2D


array corresponds to two subscript values, and so on.

• It is an ordered sequence composed of n (n>1) data


elements (a1,a2,…,an) with the same data type
• The sequence must be stored in a memory unit with
consecutive addresses
Arrays

• The data elements in the array have the same data


type

• An array is a random access structure.


• Given a set of subscripts, you can access the
corresponding data elements

• The number of data elements in the array is fixed


2.1 The array as an ADT (1/6)

• Arrays
• Array:
• a set of pairs,

• data structure
• For each index, there is a value associated with that index.

• representation (possible)
• Implemented by using consecutive memory.

• In mathematical terms, we call this a correspondence or a mapping.


Definition
• Use continuous memory space
• One of the method to represent an ordered sequence
• Each element has the same data type.
• Support Random Access and Sequential Access
• It is more troublesome when inserting or deleting elements because
other elements need to be moved
int A[5];

陣列名稱 A
陣列註標 0 1 2 3 4
陣列元素 A[0] A[1] A[2] A[3] A[4]

7
D i f f e re n c e b e t w e e n v a r i a b l e
declaration and array declaration
variable declaration array declaration
int A, B, C; int A[3];
主記憶體

變數1: A
A陣列
A[0] A[1] A[2]
變數2: B

變數3: C

Discontinuous memory Contiguous Memory Space


space allocation Allocation 8
Advantages and disadvantages of
array structure

Advantages Disadvantages
• Deletion and insertion cause
• Ease of use
frequent data movement
• Use index value to quickly
• Waste unnecessary memory
access data
• A large amount of data can be • Array length is constant, may
processed at one time not be enough
• Easier to express data
processing skills

9
Storage of array
• Add "label" or "index" directly after the array name
• [Example]: Declare an array of A[3] and store 10, 20, 30 respectively,
as shown below:
int A[3];
A[0]=10; //指把10指定給A陣列中的第0項的資料中
A[1]=20;
A[2]=30;
A陣列 10 20 30

A[0] A[1] A[2]

• Arrays are more flexible than variables


• When the label is "variable": if the variable x=1, then A[x]=20
• When the label is "computational formula": if the formula is x*2, then A[x*2]=30
• When the label is "array element": if B[0]=1, then A[B[0]]=20

10
Example
• Please input the grades of six students into the array in sequence, and
calculate and output the sum
成績
1 60
2 70
3 80
4 85
5 90
6 100

11
Array, but not using the for loop
algorithm
main()
{
//宣告
int A[6]={60,70,80,85,90,100};
int sum;
//處理
sum = A[0] + A[1] + A[2] + A[3] + A[4] + A[5];
//輸出
printf(“總和為:%3d",sum);
printf("\n");
system("PAUSE");
return(0);
}

12
Array, using the for loop algorithm
(best)
main()
{
//宣告
int A[6]={60,70,80,85,90,100};
int i,sum=0;
//處理
for (i = 0; i<=5;i++ )
sum+=A[i];
//輸出
printf(“總和為:%3d",sum);
printf("\n");
system("PAUSE");
return(0);
}

13
Five commonly used operation
instructions for one-dimensional
arrays
• Read

• Write

• Insert

• Delete

• Copy

14
Read
• [Definition] Use Index to "read" data
• [Example] Put the second element of the A array into the X
variable
• [Writing] X = A[1]; //The annotation of the array starts from
0

A陣列 10 20 30

A[0] A[1] A[2]

X
20

15
Write
• [Definition] Use index to "write" data
• [Example] Write the value 50 to the second index position of
the A array
• [Writing] A[1] = 50; //The annotation of the array starts from
0 寫入前:
A陣列 10 20 30

A[0] A[1] A[2]

寫入後: 寫入50到A[1]
A陣列 10 20->50 30

A[0] A[1] A[2]

16
50
Insert(1/2)
• [Definition] Insert a new element at the position i, the original label i
and its following elements must be moved back one position
• [Example] A new element will be inserted at the position marked 1
(15)
• [algorithm]

17
Insert(2/2)
• [Illustration]
差入前: A[1]的內容為20
A陣列 10 20 30

A[0] A[1] A[2]


往後挪一個位置
2 1
差入後:
A陣列 10 20 30消失
A[0] A[1] A[2]

差入後: 插入15到A[1]
3
A陣列 10 15 20

A[0] A[1] A[2]

18
Delete(1/2)
• [Definition] means to delete the specified element marked i.
The original element marked i is deleted. In order to avoid
wasting memory space, all subsequent elements must be
moved forward by one position
• [Example] delete an old element at position 1 (20)
• [algorithm]

19
Delete(2/2)
• [Illustration]
刪除前: A[1]的內容為20
A陣列 10 20 30

A[0] A[1] A[2]

刪除後:
1
A陣列 10 20 30

A[0] A[1] A[2]

2
刪除後: 插入15到A[1]
A陣列 10 30 3 0

A[0] A[1] A[2]

20
Copy(1/2)
• [Definition] refers to copying all the values in the elements of
the source array to the destination array one by one
• [Example] Copy all the values in the elements of array A to
array B one by one
• [algorithm]

21
Copy(2/2)
• [Illustration]

來源陣列:
A陣列 10 20 30

A[0] A[1] A[2]

複製(Copy)
目的陣列:
B陣列 10 20 30

A[0] A[1] A[2]

22
2.1 The array as an ADT (2/6)

• When considering an ADT we are more concerned


with the operations that can be performed on an
array.
• In addition to create a new array, most programming
languages provide only two standard operations for arrays,
retrieves, and stores.
• Structure 2.1 shows a definition of the array ADT
• The advantage of this ADT definition is that it clearly
points out the fact that the array is a more general structure
than “a consecutive set of memory locations.”
2.1 The array as an ADT (3/6)
2.1 The array as an ADT (4/6)
• Arrays in C
• int list[5], *plist[5];
• list[5]: (five integers) list[0], list[1], list[2], list[3], list[4]
• *plist[5]: (five pointers to integers)
• plist[0], plist[1], plist[2], plist[3], plist[4]
• implementation of 1-D array
list[0] base address = a
list[1] a + sizeof(int)
list[2] a + 2*sizeof(int)
list[3] a + 3*sizeof(int)
list[4] a + 4*sizeof(int)
2.1 The array as an ADT (5/6)

• Arrays in C (cont’d)
• Compare int *list1 and int list2[5] in C.
Same: list1 and list2 are pointers.
Difference: list2 reserves five locations.
• Notations:
list2 - a pointer to list2[0]
(list2 + i) - a pointer to list2[i] (&list2[i])
*(list2 + i) - list2[i]
2.1 The array as an ADT (5/6)

• Arrays in C (cont’d)

程序 2.1程序舉例
2.1 The array (6/6)

• Example:
1-dimension array addressing
• int one[] = {0, 1, 2, 3, 4};
• Goal: print out address and value
• void print1(int *ptr, int rows) {
/* print out a one-dimensional array using a pointer */
int i;
printf(“Address Contents\n”);
for (i=0; i < rows; i++)
printf(“%8u%5d\n”, ptr+i, *(ptr+i) );
printf(“\n”);
}
results
2.2 Dynamic storage allocation for
arrays
• 2.2.1 1-dimension array

程序1.4選擇排序
2.2 Dynamic storage allocation for
arrays
• 2.2.1 1-dimension array

程序1.4選擇排序
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• Declaration of two-dimensional array

• Storage structure

"Array of Arrays"
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• Constructs a two-dimensional array
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• Constructs a two-dimensional array
• the following statement for the usage of this program
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• Constructs a two-dimensional array
• The other two memory allocation functions
• calloc

• realloc
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• calloc
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• CALLOC macro definition
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• realloc
• realloc function can resize the storage space allocated by malloc
or calloc.

• instruction
2.2 Dynamic storage allocation for
arrays
• 2.2.1 2-dimension array
• REALLOC macro definition
N-dimensional Array

• Take a two-dimensional array as an example


• Set 2D array A=(aij)m´n, then A=(α1,α2,…,αp)
(p=m或n), in which each data element αj is a column
vector (Linear List):
αj =(a1j ,a2j ,…,amj) 1≦ j ≦ n
• Or a row vector:
αi =(ai1 ,ai2 ,…,ain) 1≦i≦m
N-dimensional Arraya11 a12 … a1n
a11 a12 … a1n
a21 a22 … a2n
a21 a22 … a2n
A= … … … … … A=
……………
am1 am2 … amn am1 am2 … amn
(a) matrix representation (b) 1D array form of column
vector
a11 a12 a1n
a21 a22 ┆ a2n
A= ┆ ┆ ┆ ┆
am1 am2 ┆ amn
(c) 1D array form of row vector
Figure 2D array legend
Sequential representation and
implementation

• In general, arrays do not perform insertion and


deletion operations.

• Once the array is established, the number of


elements in the structure and the relationship
between elements will not change

• Therefore, the method of sequential storage is


generally used to represent the array.
Array representation in memory

• 1D array

• 2D array

42
1D array
• If the A array has N elements, the starting address of
the array is L0, and the index value starts from 0, and
d is the element size, what is the starting position of
A[i]? A array 0 1 2 … i N-1

d d

L0 L0+2d L0+i*d

L0 is the starting address


d is the element size
The position of A[i] = L0+i*d

43
Exercise

• Assuming that each integer occupies 2 bytes, if the


starting address of the A array starts from 100, what
is the starting address of A[5]?
• Let L0 = 100, d = 2

44
Index starts from L
• If the index of the A array is from L to U, the
starting address of the array is L0, and d is the
element size, what is the starting position of A[i]?
L L+1 L+2 … i U
A陣列
d d

L0 L0+2d L0+(i – L)*d

L0 is the starting address


d is the element size
The position of A[i] is L0+(i – L)*d

45
2D array

• Declaration : A[0…M-1, 0…N-1]


• in which:
M represents the number of columns (Row), horizontal
Ο 圖的儲存位置: A[1,4]
N represents the number of columns (Column), vertical Δ 圖的儲存位置:A[2,1]
Therefore, there are a total of M*N grids ☐圖的儲存位置:A[M-1, N-2]
0 1 2 3 4 …… N - 2 N - 1
0
1 Ο
2 Δ
.
.
.
M-2
M-1 ☐ 46
2D -> 1D

• In a 2D array, how to convert a 2D array into a 1D


array, there are two ways::
• Row Major
• Column Major

47
Sequential representation and
implementation

• Question: How to store the data of the array


according to the memory structure? Hint: Array elements must be
arranged in a sequence in a
certain order, and then this
• There are two sequential storage methods linear sequence is stored in
memory

• Row Major Order


• Column Major Order
Sequential representation and
implementation

• Row Major Order


• Arrange array elements in rows
• The i+1th row vector comes immediately after the ith row
vector.
• For two-dimensional arrays, the linear sequence stored in
row-major order is:
• a11,a12,…,a1n, a21,a22,…a2n ,……, am1,am2,…,amn
Row-major
0 1 2 ……. N-1 主記憶體

0 A[0, 0]

1 A[0, 1]
.
2 .
.
3
A[0, N-1]
.
.
. A[1, 0]
.
.
. A[1, 1]
.
. .
. .
.
M-1
A[M-1, N-1]

邏輯位置 實體位置

由上而下一列一列讀入一維陣列 50
Row-major
0 1 2 ……. N-1

0 • 令L0為起始位置
• d為元素大小
1
i row 則A[i, j]的位置 = L0 + [i * N + j] * d
2
Δ的位置為:
3
Δ A[3, 2] = L0 + [3 * N + 2] * d
A[i, j]
.
.
.
j column
.
.
.
.
.
.

M-1

51
Sequential representation and
implementation

• Column Major Order


• Arrange array elements in columns
• The j+1th column vector comes immediately after the jth
column vector.
• For two-dimensional arrays, the linear sequence stored in
column-major order is:
• a11,a21,…,am1, a12,a22,…am2, ……, an1,an2,…,anm
Column-major
0 1 2 ……. N-1 主記憶體

0 A[0, 0]

1 A[1, 0]
.
2 .
.
3
A[M-1,0]
.
.
. A[0, 1]
.
.
. A[1, 1]
.
. .
. .
.
M-1
A[M-1, N-1]

邏輯位置 實體位置

由上而下一列一列讀入一維陣列 53
Column-major
0 1 2 ……. N-1

0 • 令L0為起始位置
• d為元素大小
1
i row 則A[i, j]的位置 = L0 + [j * M + i] * d
2
Δ的位置為:
3
Δ A[3, 2] = L0 + [2 * M + 3] * d
A[i, j]
.
.
.
.
.
.
.
.
.

M-1

54
j column
… …
a11 a12 … a1n
S ea21
q ua22e n…t iaa2n l r e p r eaa11s12 e n t第a t i o naa1121 a n第d
A=implementation
…………… 1 1
… 行 … 列
am1 am2 … amn a1n am1

(a) Representation of a
a21 a12
two-dimensional array a22 第 a22 第
2 2
… 行 … 列
a2n am2

┆ ┆ ┆ ┆
am1 a1m
am2 第 a2m 第
m n
… 行 … 列
Amn amn
Figure Two-dimensional array and its
sequential storage legend
… …
(b) row-major (c) Column-major
Sequential representation and
implementation
• Assuming a two-dimensional array A=(aij)m´n, if the number of
storage units occupied by each element is l (units). LOC[a11]
represents the first address of element a11 (the first address of
the array)
• 1. Store in "row-major order"
• (1) The (first) address corresponding to each element in row 1 is:
• LOC[a1j]=LOC[a11]+(j-1)´l j=1,2, …,n
• (2) The (first) address corresponding to each element in row 2 is:
• LOC[a2j]=LOC[a11]+n´l +(j-1)´l j=1,2, …,n
………
• (3) The (first) address corresponding to each element in row m is:
• LOC[amj]=LOC[a11]+(m-1)´n´l +(j-1)´l j=1,2, …,n
• It can be seen from this that the (first) address of any element aij in the two-
dimensional array is:
• LOC[aij]=LOC[a11]+[(i-1)´n +(j-1)]´l i=1,2, …,m j=1,2, …,n
Sequential representation and
implementation
• Assuming a two-dimensional array A=(aij)m´n, if the number of
storage units occupied by each element is l (units). LOC[a11]
represents the first address of element a11 (the first address of
the array)
• 2. Store in "column -major order"
• (1) The (first) address corresponding to each element in column 1 is:
• LOC[aj1]=LOC[a11]+(j-1)´l j=1,2, …,m
• (2) The (first) address corresponding to each element in column 2 is:
• LOC[aj2]=LOC[a11]+m´l +(j-1)´l j=1,2, …,m
………
• (3) The (first) address corresponding to each element in row m is:
• LOC[ajn]=LOC[a11]+ (n-1)´m´l +(j-1)´l j=1,2, …,m
• It can be seen from this that the (first) address of any element aij in the two-
dimensional array is:
• LOC[aij]=LOC[a11]+[(i-1)´m+(j-1)]´l i=1,2, …,m j=1,2, …,n
Sequential representation and
implementation
• Assuming a two-dimensional array A=(aij)m´n, if the number of
storage units occupied by each element is l (units). LOC[a11]
represents the first address of element a11 (the first address of
the array)
• For three-dimensional arrays A=(aijk)m´n´p, if the number of
storage units occupied by each element is l (units),
LOC[a111] represents the first address of element a111, that is,
the first address of the array.
• To store in "row-major order".
• The address of any element aijk in the three-dimensional array is:
• LOC(aijk)=LOC[a111]+[(i-1)´n´p+(j-1)´p+(k-1)]´l
Sequential representation and
implementation
• Assuming a two-dimensional array A=(aij)m´n, if the number of
storage units occupied by each element is l (units). LOC[a11]
represents the first address of element a11 (the first address of
the array)
• For n-dimensional arrays A=(aj1j2…jn) , if the number of
storage units occupied by each element is l (units), LOC[a11
…1] represents the first address of element a11 …1, that is, the
first address of the array.
• To store in "row-major order".
• The address of any element aj1j2…jn in the n-dimensional array is:
• LOC[aj1j2…jn]=LOC[a11 …1]+[(b2´…´bn)´(j1-1)
+ (b3´…´bn)´(j2-1)+ …
+ bn´(jn-1-1)+ (jn-1)] ´l
2.3 Structures and Unions (1/6)

• 2.3.1 Structures (Records)


• Arrays are collections of data of the same type.
• In C, there is an alternate way of grouping data that permit
the data to vary in type.
• This mechanism is called the struct, structure’s abbreviation.
• A structure is a collection of data items, where each item is
identified as to its type and name.
2.3 Structures and Unions (2/6)

• Create structure data type


• We can create our own structure data types by using the
typedef statement as below:

• human_being is the name of the type defined by the structure


definition
• We can use this definition to declare the variable, such as:
human_being person1, person2;
2.3 Structures and Unions (2/6)

• Create structure data type


• if (persion1 == person2)
• Determines whether two structures are exactly equal
• The structure cannot be compared for equality, we can only use functions
to implement

Statements that call a function

程序2.4检查两个结构相等的函数

• persion1 = perosn2
2.3 Structures and Unions (2/6)

• Create structure data type


• if (persion1 == person2)
• persion1 = perosn2
• ANSI C allows the overall assignment of structures, but the early C
language does not allow it, and can only assign values in the following
sentence:
2.3 Structures and Unions (3/6)
Memory Layout
• We can also embed a structure within a structure.

char name[10]
Memory Layout
human_being

int age
date int month
float salary
int day
int month
int year date
int day
int year

• A person born on February 11, 1994, would have have values for the date
struct set as
2.3 Structures and Unions (4/6)
• 2.3.2 Unions
• A union declaration is similar to a structure.
• The fields of a union must share their memory space.
• Only one field of the union is “active” at any given time

Memory Layout
sex_type

enum tag_field
u int children int beard

person1.sex_info.sex = male;
person1.sex_info.u.beard = FALSE;
and
person2.sex_info.sex = female;
person2.sex_info.u.children = 4;
2.3 Structures and Unions (5/6)

• 2.3.3 Internal implementation of structures

• The fields of a structure in memory will be stored in the


same way using increasing address locations in the order
specified in the structure definition.
• Holes or padding may actually occur
• Within a structure to permit two consecutive components to be
properly aligned within memory
• The size of an object of a struct or union type is the amount of storage
necessary to represent the largest component, including any padding
that may be required.
2.3 Structures and Unions (6/6)
• 2.3.4 Self-Referential Structures
• One or more of its components is a pointer to itself.

• typedef struct list { Construct a list with three nodes


char data; item1.link=&item2;
list *link; item2.link=&item3;
} malloc: obtain a node (memory)
free: release memory
• list item1, item2, item3;
item1.data=‘a’;
item2.data=‘b’; a b c
item3.data=‘c’;
item1.link=item2.link=item3.link=NULL;

You might also like