26
PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: [email protected] Tel: 04-7232105 ext.3242 彰彰彰 彰彰彰 彰彰彰 (Cheng-Jung Tsai )

PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: [email protected] Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

Embed Size (px)

Citation preview

Page 1: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

PRACTICAL DATA STRUCTURES USING

C/C++

Chapter 3Numeric Arrays

Email: [email protected]: 04-7232105 ext.3242

彰師大 數學系蔡政容 (Cheng-Jung Tsai)

Page 2: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

2

Outline

3.1 initializing numeric arrays3.1 initializing numeric arrays 3.2 passing arrays between functions3.2 passing arrays between functions 3.3 operations on numeric arrays3.3 operations on numeric arrays 3.4 sorting with numeric arrays3.4 sorting with numeric arrays 3.5 multidimensional numeric arrays3.5 multidimensional numeric arrays 3.6 eight-queens puzzle3.6 eight-queens puzzle

Page 3: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

3

3.1 initializing numeric arrays

Basic idea: Int array[3]: contains three elements array[0], array[1],

array[2] array vs. &array[0]

Return the same value: the address of the first element of the array

See Program 3.1 & Fig. 3.1 Int uses two 8-bit memory locationstwo 8-bit memory locations (a char use one lo

cations) See Program 3.2 & Fig. 3.2

Page 4: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

4

initializing numeric arrays

Inside array Local declaration

Declare array Inside main() See Program 3.3

Global declaration: array initializationarray initialization Declare array outside main() See Program 3.4

Use keyword “static” Static int array[3] See page 69 Not a good way since static has other features, such as con

trol over the variables’ lifetime

Page 5: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

5

initializing numeric arrays

Putting in your own values See Program 3.5

Use pointer See Program 3.6 Note that *ptr is declared as type int. This lets the complier k

now that every increment of *ptr is to be two bytes not one

Page 6: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

6

3.2 passing arrays between functions

Array passing: See Program 3.7

Passing address Note the code: functioin1(array) array denotes the beginning address of the array See Fig. 3.3

Passing numeric arrays back The passing of an array from a called function

See Program 3.8 See Fig. 3.4

Page 7: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

7

3.3 operations on numeric arrays

Working with the array index See Program 3.9

Changing the sequence Program 3.10

Finding a minimum value See Program 3.11

Swapping elements of an array See Fig. 3.5 to see how a swap Program 3.12

Searching an array See Fig. 3.5 to see how a swap Program 3.12

Page 8: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

8

3.4 sorting with numeric arrays

Examined several sorting techniques Bubble sortBubble sort Bucket sortBucket sort Merge sortMerge sort Quick sortQuick sort

The number of comparisonsnumber of comparisons is also shown to evaluate the efficiency of each sorting techniques

Page 9: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

9

Bubble sort

Bubble sorting rules See Page 84 See Program 3.14 Program analysis

See pages 87 to 89 Time complexity: O(nTime complexity: O(n22))

Page 10: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

10

Bucket sort

Can be used only in limited sorting situations Requires the amount of numbers to be within a predetermined rangeRequires the amount of numbers to be within a predetermined range None of the numbers is duplicatedNone of the numbers is duplicated

Example See page 89 6 7 5 8 4 9 3 0 2

None of the numbers is larger than 9 None of the numbers is duplicated

Initialize a ten-element bucket arrayten-element bucket array For each element in the input, we set the associated element i

n the bucket array equal to 1 See Figures 3.6 to 3.8 in page 89

See Program 3.15 Time complexity: O(n)Time complexity: O(n) Memory complexity: O(n)Memory complexity: O(n)

Page 11: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

11

Merge sort

Has an efficiency that falls somewhere between those of bucket and bubble sorts The savings in the number of comparisons comes from the The savings in the number of comparisons comes from the

fact that the entire list of input numbers is divided into smallfact that the entire list of input numbers is divided into smaller listser lists

Split & sort and then mergeSplit & sort and then merge Split: See Figures 3.9 & 3.10 Merge: See example in page 92 and Figure 3.11

See Program 3.16 Recursion is used The number of comparisons is composed of two portions: t

he comparisons made when the array are subdivided, and that when they are merged

Time complexity: O(nlogn)Time complexity: O(nlogn)

Page 12: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

12

Merge sort

High memory complexity: The main disadvantage of merge sort is that it requ it requ

ires a substantial memoryires a substantial memory Memory complexity: O(n)Memory complexity: O(n) There are a total nine copies of merge_sort() in me

mory simultaneously.See pages 95 to 96

Useful for small arraysAn large array would surely eat up all available m

emory before sorting could be completed

Page 13: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

13

Time complexity of Merge sort: O(nlogn)

split: T(n)=2T(n/2),T(1)=O(1) merge: C(n)=O(n) N>1 時T(n)=2T(n/2)+O(n)

=4T(n/4)+2O(n/2)+O(n)

=8T(n/8)+4O(n/4)+2O(n/2)+O(n)

=2^lognT(1)+O(n)+O(n)...+O(n)[ 一共 logn 個 O(n)]

= O(nlogn)

Page 14: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

14

Quick sort

A divide and conquerdivide and conquer algorithm, Is generally regarded as the most efficient for large or random array

pivot(中樞 ) The main idea behind quick sort is to choose an array partitioning element (the f

irst element of the initial array) See Figure 3.12

See Program 3.17 in pages 97 to 99 Recursion is used The number of comparisons only comes from the comparisons made when the

array are subdivided The order of the array elements has an effect on the efficiency

In an ideal quick sort application, the median element is chosen as the pivot, instead of the first array element

See page 99 to 100 to see an example Time complexity: Time complexity:

average/best case : O(nlogn) worst case : O(n2) : 資料的順序完全相反時

Page 15: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

15

Quick sort: Built-in function in C/C++: qsort()

Quick sort is a built-in function contained in <stdlib.h> in C/C++: qsort()

Needs four parametersqsort(inarray,n,sizeof(inarrary[0]),cmp)

A pointer to the array to be stored The size of the array The size of elements in the array

Can sort int, float, double A compare function

Must satisfy some conditions in page 100 See Program 3.18 Note the use of type casting ( 型態轉換 ) *((int*)a) in cmp()

Page 16: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

16

supplementary 將最左邊的數設定為軸,並記錄其值為 s 廻圈處理:

1. 令索引 i 從數列左方往右方找,直到找到大於 s 的數 2. 令索引 j 從數列右方往左方找,直到找到小於 s 的數 3. 如果 i >= j ,則離開迴圈 4. 如果 i < j ,則交換索引 i 與 j 兩處的值 5. 將左側的軸與 j 進行交換 6. 對軸左邊進行遞迴 7. 對軸右邊進行遞迴

透過以下演算法,則軸左邊的值都會小於 s ,軸右邊的值都會大於 s ,如此再對軸左右兩邊進行遞迴,就可以對完成排序的目的,

實例, * 表示要交換的數, [] 表示軸:[41]   24   76*   11   45   64   21   69   19   36* [41]   24   36   11   45*   64   21   69   19*   76 [41]   24   36   11   19   64*   21*   69   45   76 [41]   24   36   11   19   21   64   69   45   76 21   24   36   11   19   [41]   64   69   45   76

41 左邊的值都比它小,而右邊的值都比它大,如此左右再進行遞迴至排序完成

Page 17: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

17

3.5 Multidimensional numeric arrays Single dimension

See Program 3.19 See Program 3.20

Two dimensions: matrix array [row][column] array [2] [3]

Two rows and three columns See Program 3.21 & Figure 3.13

Row-major orderRow-major order The complier lays out memory is to lay out one row at a tim

e with a given number of columns See Figure 3.14

Page 18: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

18

Array applications

It is important to develop programming skills that allow calculations with arrays

The sum of the first column of the two-dimensional array See Program 3.22 Note the code: add_column (int arrayin [] [3])

C/C++ requires that the limits of other dimensions be specified within the formal parameter list

The reason is that the complier needs to know how many columns will be required for each row

Page 19: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

19

Adding more columns

Adds all columns of the given matrix The expansion of Program 3.22 See Program 3.23 Note the code: add_columns (int arrayin [] [3], .....)

Adding each column and each row See Program 3.24 Note the codes: add_columns (int arrayin [] [3], ....) and

add_rows (int arrayin [] [3],....)

Page 20: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

20

The multiplying of two matrices

Matrix multiplication is useful since we are often required to multiply matrices together to get a desired result.

The number of columns in the first matrix must equal to the number of rows in the second matrix See Figures 3.15 & 3.16

A[2][3]*B[3][4]OK C[1][4]*D[4][2]OK E[2][3]*F[4][3]Error

A[i][k]*B[k][j]X[i][j] See Program 3.25

Page 21: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

21

Dynamic linking

A technique used for efficient storage and retrieval of disk files. It is used in conjunction with a special area on the disk called the file file

allocation table (FAT)allocation table (FAT) FAT is a block of numbers describing how sectors on the disk have allocated

Free sector Allocated sector Bad sector Final sector in a file

With FAT, files need not be stored in consecutive sectors Sector 0 is not assigned since it is where we are storing the FAT See example in page 114

0 0 5 4 2 13 12 90 99 0 0 99 6 0 0

See Program 3.26 See page 116 to see some problems in the FAT in program 3.26

The fourth sector of file #4 does not exist No other entries in the FAT contain 12

Page 22: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

22

A histogram generator

A histogram contains the frequency of occurrence for each different data value See example in page 116 See Program 3.27 Note the built-in function rand() in <stdlib.h>

Rand() returns an integer in the range 0 to RAND_MAC RAND_MAC is predefined in <stdlib.h>

Page 23: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

23

Finding standard deviation

See Program 3.28

Page 24: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

24

Magic squares

A magic squaremagic square is a square matrix having an odd number having an odd number of rows and columns, whose rows and columns (and even of rows and columns, whose rows and columns (and even both diagonals) add up to the same valueboth diagonals) add up to the same value The number of columns in the first matrix must equal to the

number of rows in the second matrix How to generate a magic square ?

Begin with 1 in the middle element of the first row Always move up and to the left one position when writing the

next element the top row (column) and bottom row (column) are next to each other

If the new position is already occupied, return to the previous position and go down one row and resume

See Program 3.29

6 1 87 5 32 9 4

Page 25: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

25

3.6 eight-queens puzzle

Place eight Queens on a chessboard, none of them none of them occupy the same row, column, or diagonaloccupy the same row, column, or diagonal

Too many different ways to place the eight Queens, 88 different patterns, which is over 16.7 million

Use backtrackingbacktracking to solve this problem Taking a step backwards when you make a wrong turn

Algorithm Pick a position for the queen If legal, go to next row If illegal, pick the next position If no legal position is found, back up one row

Page 26: PRACTICAL DATA STRUCTURES USING C/C++ Chapter 3 Numeric Arrays Email: cjtsai@cc.ncue.edu.tw Tel: 04-7232105 ext.3242 彰師大 數學系 蔡政容 (Cheng-Jung Tsai)

26

eight-queens puzzle

See Program 3.30 in pages 124 to 126 Note the function solve_row(int r) in page 122

Recursion is used Note the function legal(int r, intc) in page 123

See Figure 3.18 to see the 8 search directions dirs[8][2] used in legal(int r, int c)