CHAPTER 21 ARRAYS AND STRUCTURES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of.

Slides:



Advertisements
Similar presentations
Divide-and-Conquer. 什麼是 divide-and-conquer ? Divide 就是把問題分割 Conquer 則是把答案結合起來.
Advertisements

6-1 指標簡介 6-2 指標與陣列 6-3 動態配置記憶體 6-4 本章綜合練習
布林代數的應用--- 全及項(最小項)和全或項(最大項)展開式
第七章 抽樣與抽樣分配 蒐集統計資料最常見的方式是抽查。這 牽涉到兩個問題: 抽出的樣本是否具有代表性?是否能反應出母體的特徵?
: A-Sequence 星級 : ★★☆☆☆ 題組: Online-judge.uva.es PROBLEM SET Volume CIX 題號: Problem D : A-Sequence 解題者:薛祖淵 解題日期: 2006 年 2 月 21 日 題意:一開始先輸入一個.
1 集合論 Chapter 3. 2 Chapter 3 Set Theory 3.1 Sets and Subsets A well-defined collection of objects (the set of outstanding people, outstanding is very.
Reference, primitive, call by XXX 必也正名乎 誌謝 : 部份文字取於前輩 TAHO 的文章.
What is static?. Static? 靜態 ? class Test { static int staticX; int instanceX; public Test(int var1, int var2) { this.staticX = var1; this.instanceX =
大綱 陣列 結構和聯結 多項式抽象資料型態 稀疏矩陣抽象資料型態 上三角和下三角表示法.
1.1 線性方程式系統簡介 1.2 高斯消去法與高斯-喬登消去法 1.3 線性方程式系統的應用(-Skip-)
第一章 變數、常數及資料型態. 變數 C 程式語言的變數名稱 第一個字必須是英文字母或底線 (_) 之後可以是數字, 英文字母或底線 (_) 不可以是保留字 例: Num (Ο) _score (Ο) C&C (X) 8num (X)
STAT0_sampling Random Sampling  母體: Finite population & Infinity population  由一大小為 N 的有限母體中抽出一樣本數為 n 的樣 本,若每一樣本被抽出的機率是一樣的,這樣本稱 為隨機樣本 (random sample)
1. 假設以下的敘述為一未提供 “ 捷徑計算 ” 能力的程式段,試用程 式設計的技巧,使此敘述經此改 寫的動作後,具有與 “ 捷徑計算 ” 之 處理方法相同之處理模式。 if and then E1 else E2 endif.
第 18 章 名稱空間與例外處理 18-1 名稱空間 18-1 名稱空間 18-2 例外處理 18-2 例外處理.
8.1 何謂高度平衡二元搜尋樹 8.2 高度平衡二元搜尋樹的加入 8.3 高度平衡二元搜尋樹的刪除
McGraw-Hill/Irwin © 2003 The McGraw-Hill Companies, Inc.,All Rights Reserved. 肆 資料分析與表達.
第 1 章 PC 的基本構造. 本章提要 PC 系統簡介 80x86 系列 CPU 及其暫存器群 記憶體: Memory 80x86 的分節式記憶體管理 80x86 的 I/O 結構 學習組合語言的基本工具.
Chapter 13 塑模靜態觀點:物件圖 Static View : Object Diagram.
Introduction to Java Programming Lecture 17 Abstract Classes & Interfaces.
第九章 結構. 結構的宣告 結構 它是由許多不同 ( 或相同 ) 資料型態的變數所組成的 集合,通常利用結構標籤稱呼此集合 struct student { char *name; int score; }; struct 為保留字,表示結構的宣告開始 結構項目需定義於大括號「 { } 」內 結尾需加上分號.
最新計算機概論 第 5 章 系統程式. 5-1 系統程式的類型 作業系統 (OS) : 介於電腦硬體與 應用軟體之間的 程式,除了提供 執行應用軟體的 環境,還負責分 配系統資源。
Introduction to Java Programming Lecture 10 Array I Declaring, Creating, and Initializing Arrays.
Hung-Hsiang WuWindows Processing Design1 Chapter 3 基本觀念 變數宣告與型態 特殊運算子符號 字串與數值的轉換 類別與物件的觀念 建立新的專案 WinMain 程式進入點 Include Header File.
: Happy Number ★ ? 題組: Problem Set Archive with Online Judge 題號: 10591: Happy Number 解題者:陳瀅文 解題日期: 2006 年 6 月 6 日 題意:判斷一個正整數 N 是否為 Happy Number.
: Fast and Easy Data Compressor ★★☆☆☆ 題組: Problem Set Archive with Online Judge 題號: 10043: Fast and Easy Data Compressor 解題者:葉貫中 解題日期: 2007 年 3.
Digital Signal Processing with Examples in M ATLAB ® Chap 1 Introduction Ming-Hong Shih, Aug 25, 2003.
第十章 再論結構. 指標與結構的關係 /* File name: ex10-1a.c */ #include int main() { struct student { char *name; int score; }; struct student st= {"Brian", 97}; struct.
: Multisets and Sequences ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 11023: Multisets and Sequences 解題者:葉貫中 解題日期: 2007 年 4 月 24 日 題意:在這個題目中,我們要定義.
:Nuts for nuts..Nuts for nuts.. ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 10944:Nuts for nuts.. 解題者:楊家豪 解題日期: 2006 年 2 月 題意: 給定兩個正整數 x,y.
1. 假設以下的敘述為一未提供 “ 捷徑計算 ” 能力的程式段,試用程 式設計的技巧,使此敘述經此改 寫的動作後,具有與 “ 捷徑計算 ” 之 處理方法相同之處理模式。 if and then E1 else E2 endif.
資料結構實習-一 參數傳遞.
第六章 陣列.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2008.
Section 4.2 Probability Models 機率模式. 由實驗看機率 實驗前先列出所有可能的實驗結果。 – 擲銅板:正面或反面。 – 擲骰子: 1~6 點。 – 擲骰子兩顆: (1,1),(1,2),(1,3),… 等 36 種。 決定每一個可能的實驗結果發生機率。 – 實驗後所有的實驗結果整理得到。
函式 Function Part.2 東海大學物理系‧資訊教育 施奇廷. 遞迴( Recursion ) 函式可以「呼叫自己」,這種動作稱為 「遞迴」 此程式的執行結果相當於陷入無窮迴圈, 無法停止(只能按 Ctrl-C ) 這給我們一個暗示:函式的遞迴呼叫可以 達到部分迴圈的效果.
845: Gas Station Numbers ★★★ 題組: Problem Set Archive with Online Judge 題號: 845: Gas Station Numbers. 解題者:張維珊 解題日期: 2006 年 2 月 題意: 將輸入的數字,經過重新排列組合或旋轉數字,得到比原先的數字大,
Structural Equation Modeling Chapter 6 CFA 根據每個因素有多重指標,以減少 測量誤差並可建立問卷的構念效度 驗證性因素分析.
Chapter 10 m-way 搜尋樹與B-Tree
本章重點 2-1 有序串列(Ordered List) 2-2 介紹陣列(array) 2-3 矩陣(matrix)的應用
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009.
2005/7 Linear system-1 The Linear Equation System and Eliminations.
5 重複迴圈 5.1 增減運算符號 增量運算符號 減量運算符號
中序轉後序 藉由由左向右掃瞄中序運算式產生後序運算式,遇到 運算元就直接輸出,遇到運算符號則先存入堆疊,將 優先權較高者輸出。 範例: a + b * c TokenStack [0] [1] [2] topoutput aa ++0a b+0ab *+ *1ab c+ *1abc eosabc*+
Visual C++重點複習.
資料結構實習-六.
1 Introduction to Java Programming Lecture 3 Mathematical Operators Spring 2008.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2010.
Chapter 2 Arrays and Structures Instructors: C. Y. Tang and J. S. Roger Jang All the material are integrated from the textbook "Fundamentals of Data Structures.
: Finding Paths in Grid ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11486: Finding Paths in Grid 解題者:李重儀 解題日期: 2008 年 10 月 14 日 題意:給一個 7 個 column.
1 Introduction to Java Programming Lecture 3 Mathematical Operators Spring 2009.
第 1 章 PC 的基本構造. 本章提要 PC 系統簡介 80x86 系列 CPU 及其暫存器群 記憶體: Memory 80x86 的分節式記憶體管理 80x86 的 I/O 結構 學習組合語言的基本工具.
: How many 0's? ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11038: How many 0’s? 解題者:楊鵬宇 解題日期: 2007 年 5 月 15 日 題意:寫下題目給的 m 與 n(m
CS Data Structures Chapter 2 Arrays and Structures.
CSCE 3110 Data Structures & Algorithm Analysis Arrays and Lists.
CHAPTER 21 ARRAYS AND STRUCTURES. CHAPTER 22 Arrays Array: a set of index and value data structure For each index, there is a value associated with that.
Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract.
Advance Data Structure Review of Chapter 2 張啟中. Review of Chapter 2 Arrays 1.3 Data Abstraction and Encapsulation 2.2 The Array As An abstract Data Type.
Data Structure Sang Yong Han Chung-Ang University Spring
Data Structures & Algorithm Analysis Arrays. Array: a set of pairs (index and value) data structure For each index, there is a value associated with that.
CHAPTER 21 ARRAYS AND STRUCTURES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of.
◦ A one-dimensional array in C is declared implicitly by appending brackets to the name of a variable int list[5], *plist[5]; ◦ arrays start at index.
1 ARRAYS AND STRUCTURES. 2 Arrays Array: a set of index and value data structure For each index, there is a value associated with that index. representation.
Data Structure Sang Yong Han
CSCE 3110 Data Structures & Algorithm Analysis
CHAPTER 2 ARRAYS AND STRUCTURES
Data Structures 4th Week
Data Structures Unit-2 Engineered for Tomorrow CSE, MVJCE.
 Zero - set zero of a polynomial
CSCE 3110 Data Structures & Algorithm Analysis
Presentation transcript:

CHAPTER 21 ARRAYS AND STRUCTURES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of Data Structures in C”, Computer Science Press, 1992.

CHAPTER 22 Arrays Array: a set of index and value a collection of data of the same type data structure For each index, there is a value associated with that index representation (possible) implemented by using consecutive memory. 由 index 對應機制分成 2 類 1. 以列為主 (row major) : 在一個多維陣列中, index 的變化是由右向左的 例 : 陣列的順序 a[1][1], a[1][2], a[1][3] … 2. 以行為主 (column major) : 在一個多維陣列中, index 變化是由左向右的 例 : 陣列的順序 a[1][1], a[2][1], a[3][1] … 在程式語言中 : FORTRAN ( 以行為主 ), C ( 以列為主 ) PASCAL( 以列為主 )

CHAPTER 23 Structure Array is objects: A set of pairs where for each value of index there is a value from the set item. Index is a finite ordered set of one or more dimensions, for example, {0, …, n-1} for one dimension, {(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)} for two dimensions, etc. Functions: for all A  Array, i  index, x  item, j, size  integer Array Create(j, list) ::= return an array of j dimensions where list is a j-tuple whose ith element is the size of the ith dimension. Items are undefined. Item Retrieve(A, i) ::= if (i  index) return the item associated with index value i in array A else return error Array Store(A, i, x) ::= if (i in index) return an array that is identical to array A except the new pair has been inserted else return error end Array *Structure 2.1: Abstract Data Type Array ( p.52)

CHAPTER 24 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 =  list[1]  + 1*sizeof(int) list[2]  + 2*sizeof(int) list[3]  + 3*sizeof(int) list[4]  + 4*size(int) Memory address

CHAPTER 25 Arrays in C (Continued) 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] 陣列名稱跟指標型變數的差別 : 陣列名稱 : 儲存是陣列的開始位址且設定後就不能做修改 指標型變數 : 可以儲存位址且設定後可以去修改儲存內容 一般指標屬於指標變數,而陣列名稱則是指標常數 所以 : int a[5] a 為陣列名稱 => a=a+2; 錯誤產生 int* pa=a pa 為指標變數 => pa=pa+2; pa 為 &a[2]; OK

CHAPTER 26 Example C 語言宣告 int a 〔 20 〕,則下列何者不合理? a.*a b.* ( a+1 ) c.*a++ d.*a 〔 1 〕 【解答】 c , d *a : a 〔 0 〕 * ( a+1 ) : a 〔 1 〕 *a++ : * ( a++ ), a 為陣列名稱,屬於指標常數,不能做為目的運算元 *a 〔 1 〕 : * ( a 〔 1 〕): a 〔 1 〕為整數資料( int a 〔 20 〕),並非指標

CHAPTER 27 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”); }

CHAPTER 28 *Figure 2.1: One- dimensional array addressing (p.55) call print1(&one[0], 5)

CHAPTER 29 Example 1. A[-3..2, -1..6, 2..7, 0..5] each of its elements occupies three memory spaces starting from 123 Find the address of the element A[0,1,2,3] (1) In row major order (2) In column major order 2. 二維陣列 A ﹝ 1…u1 , 1…u2 ﹞的每一元素占用記憶體 2 位元組,開始位址為 LO ,已知﹝ 6 , 2 ﹞的儲存位址為 ( 2040 ), A ﹝ 3 , 4 ﹞的儲存位址為( 2094 ),試求 u1 : ( A ) 5 ( B ) 10 ( C ) 15 ( D )無法求得

CHAPTER 210 Answer 1.Ans. (1) In row major order 123+((0-(-3))*8*6*6+(1-(-1))*6*6+(2-2)*6+(3-0))*3= *3=2940 (2) In column major order 123+((3-0)*6*8*6+(2-2)*8*6+(1-(-1))*6+(0-(-3)))*3= *3= Ans. (C ) 因 A ﹝ 6 , 2 ﹞在 A ﹝ 3 , 4 ﹞之前,故此陣列應以 column-major 方式儲存‧ 若是 row-major ,則 A ﹝ 3 , 4 ﹞應在 A ﹝ 6 , 2 ﹞之前‧ 假設 A 〔 1 , 1 〕的儲存位址為 LO ,則: 2040= LO +〔( 2 - 1 ) ×u1 +( 6 - 1 )〕 ×2 2094= LO +〔( 4 - 1 ) ×u1 +( 3 - 1 )〕 ×2 解出: LO =2000 , u1=15 ‧

CHAPTER 211 Dynamically allocated arrays (one-dimensional) Q: How large an array to use? Larger or smaller? A: Deferring this decision to run time and allocate the array with a good estimation.

CHAPTER 212 Change the Program 1.4 to: int i,n,*list; printf( “Enter the number of numbers to generate: ”); scanf(“%d”,&n ); if (n<1){ fprintf(stderr, “Improper value of n\n” ) exit(EXIT_FAILURE ); } MALLOC(list, n*sizeof(int));

CHAPTER 213 Dynamically allocated arrays (two-dimensional) *Array of array Ex. int x[3][5]; P.S Three-dimensional array? x[0] x1] x[2] [0] [1] [2] [3] [4]

CHAPTER 214 int** make2dArray(int rows, int cols) {/* create a two dimensional rows × cols array */ int **x, I; /*get memory for row pointers */ MALLOC(x, rows * sizeof (*x)); /* get memory for each row */ for (i=0; i<rows; i++) MALLOC(x[i], cols * sizeof(**x)); return x; } Program 2.3: Dynamically create a two-dimensional array(p.57)

CHAPTER 215 Additional memory allocation functions void * calloc(size_t number, size_t size) Ex. int *x; x = calloc(n, sizeof(int))  The capacity of this array is n, and x[0:n-1] are initially 0 void * realloc(void *ptr, size_t size) Ex. realloc(p,s)  Changes the size of the memory block pointed at by p to s void * alloca(size_t size)  allocates space in the stack frame, automatically freed on return

CHAPTER 216 Structures (records) struct { char name[10]; int age; float salary; } person; strcpy(person.name, “james”); person.age=10; person.salary=35000;

CHAPTER 217 Create structure data type typedef struct human_being { char name[10]; int age; float salary; }; or typedef struct { char name[10]; int age; float salary; } human_being; human_being person1, person2; 課本寫錯 這樣不行

CHAPTER 218 Union Union 跟結構一樣也是種自訂的資料型態, 但 是它的成員共用一個相同的記憶體 儲存 Union 的記憶體大小為此 Union 最大成 員的大小 Union 可節省記憶體

CHAPTER 219 #include union un { int x; float y; }; void main() { union un u; printf("%d\n",sizeof(u)); u.x=10; printf("%d\n",u.x); u.y=10.25; printf("%d %f",u.x,u.y); }

CHAPTER 220 Self-Referential Structures One or more of its components is a pointer to itself. struct list { char data; struct list *link; }; list item1, item2, item3; item1.data=‘a’; item2.data=‘b’; item3.data=‘c’; item1.link=item2.link=item3.link=NULL; abc Construct a list with three nodes item1.link=&item2; item2.link=&item3; malloc: obtain a node 結構成員不能包含有跟自己相同結構型態的成員, 但結構定義可以包含有指向相同結構的指標

CHAPTER 221 Structure Polynomial is objects: ; a set of ordered pairs of where a i in Coefficients and e i in Exponents, e i are integers >= 0 functions: for all poly, poly1, poly2  Polynomial, coef  Coefficients, expon  Exponents Polynomial Zero( ) ::= return the polynomial, p(x) = 0 Boolean IsZero(poly) ::= if (poly) return FALSE else return TRUE Coefficient Coef(poly, expon) ::= if (expon  poly) return its coefficient else return Zero Exponent Lead_Exp(poly) ::= return the largest exponent in poly Polynomial Attach(poly,coef, expon) ::= if (expon  poly) return error else return the polynomial poly with the term inserted Polynomials A(X)=3X 20 +2X 5 +4, B(X)=X 4 +10X 3 +3X 2 +1

CHAPTER 222 Polynomial Remove(poly, expon) ::= if (expon  poly) return the polynomial poly with the term whose exponent is expon deleted else return error Polynomial SingleMult(poly, coef, expon) ::= return the polynomial poly coef x expon Polynomial Add(poly1, poly2) ::= return the polynomial poly1 +poly2 Polynomial Mult(poly1, poly2) ::= return the polynomial poly1 poly2 *Structure 2.2:Abstract data type Polynomial (p.61) End Polynomial

CHAPTER 223 /* d =a + b, where a, b, and d are polynomials */ d = Zero( ) while (! IsZero(a) && ! IsZero(b)) do { switch COMPARE (Lead_Exp(a), Lead_Exp(b)) { case -1: d = Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b)); b = Remove(b, Lead_Exp(b)); break; case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b)); if (sum) { Attach (d, sum, Lead_Exp(a)); a = Remove(a, Lead_Exp(a)); b = Remove(b, Lead_Exp(b)); } break; Polynomial Addition #define MAX_DEGREE 101 typedef struct { int degree; float coef[MAX_DEGREE]; } polynomial; data structure 1:

CHAPTER 224 case 1: d = Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a)); a = Remove(a, Lead_Exp(a)); } } insert any remaining terms of a or b into d *Program 2.4 :Initial version of padd function(p.62) advantage: easy implementation disadvantage: waste space when sparse

CHAPTER 225 Data structure 2: use one global array to store all polynomials A(X)=2X B(X)=X 4 +10X 3 +3X 2 +1 coef exp starta finisha startb finishb avail *Figure 2.2: Array representation of two polynomials (p.63) specificationrepresentation poly A B

CHAPTER 226 MAX_TERMS 100 /* size of terms array */ typedef struct { float coef; int expon; } polynomial; polynomial terms[MAX_TERMS]; int avail = 0; *(p.62) storage requirements: start, finish, 2*(finish-start+1) nonparse:twice as much as (1) when all the items are nonzero

CHAPTER 227 void padd (int starta, int finisha, int startb, int finishb, int * startd, int *finishd) { /* add A(x) and B(x) to obtain D(x) */ float coefficient; *startd = avail; while (starta <= finisha && startb <= finishb) switch (COMPARE(terms[starta].expon, terms[startb].expon)) { case -1: /* a expon < b expon */ attach(terms[startb].coef, terms[startb].expon); startb++ break; Add two polynomials: D = A + B

CHAPTER 228 case 0: /* equal exponents */ coefficient = terms[starta].coef + terms[startb].coef; if (coefficient) attach (coefficient, terms[starta].expon); starta++; startb++; break; case 1: /* a expon > b expon */ attach(terms[starta].coef, terms[starta].expon); starta++; }

CHAPTER 229 /* add in remaining terms of A(x) */ for( ; starta <= finisha; starta++) attach(terms[starta].coef, terms[starta].expon); /* add in remaining terms of B(x) */ for( ; startb <= finishb; startb++) attach(terms[startb].coef, terms[startb].expon); *finishd =avail -1; } *Program 2.5: Function to add two polynomial (p.64) Analysis:O(n+m) where n (m) is the number of nonzeros in A(B).

CHAPTER 230 void attach(float coefficient, int exponent) { /* add a new term to the polynomial */ if (avail >= MAX_TERMS) { fprintf(stderr, “Too many terms in the polynomial\n”); exit(1); } terms[avail].coef = coefficient; terms[avail++].expon = exponent; } *Program 2.6:Function to add anew term (p.65) Problem:Compaction is required when polynomials that are no longer needed. (data movement takes time.)

CHAPTER 231 The Sparse Matrix Abstract Data Type Matrix  Examples of matrix Sparse matrix  Many zero items Representation of matrix  A[][], standard representation store non-zero item only  Sparse matrix, store non-zero item only col 0col 1col 2 row row row row row col 0col 1col 2col 3col 4col 5 row row row row row row *3 6*6

CHAPTER 232 Structure Sparse_Matrix is objects: a set of triples,, where row and column are integers and form a unique combination, and value comes from the set item. functions: for all a, b  Sparse_Matrix, x  item, i, j, max_col, max_row  index Sparse_Marix Create(max_row, max_col) ::= return a Sparse_matrix that can hold up to max_items = max _row  max_col and whose maximum row size is max_row and whose maximum column size is max_col. SPARSE MATRIX ABSTRACT DATA TYPE

CHAPTER 233 Sparse_Matrix Transpose(a) ::= return the matrix produced by interchanging the row and column value of every triple. Sparse_Matrix Add(a, b) ::= if the dimensions of a and b are the same return the matrix produced by adding corresponding items, namely those with identical row and column values. else return error Sparse_Matrix Multiply(a, b) ::= if number of columns in a equals number of rows in b return the matrix d produced by multiplying a by b according to the formula: d [i] [j] =  (a[i][k]b[k][j]) where d (i, j) is the (i,j)th element else return error. * ADT 2.3: Abstract data type Sparse-Matrix (p.74)

CHAPTER 234 row col value row col value a[0] b[0] [1] [1] [2] [2] [3] [3] [4] [4] [5] [5] [6] [6] [7] [7] [8] [8] (a) (b) *Figure 2.5:Sparse matrix and its transpose stored as triples (p.75) (1)Represented by a two-dimensional array. Sparse matrix wastes space. (2)Each element is characterized by. transpose

CHAPTER 235 Sparse_matrix Create(max_row, max_col) ::= #define MAX_TERMS 101 /* maximum number of terms +1 */ typedef struct { int col; int row; int value; } term; term a[MAX_TERMS] * (P.75)

CHAPTER 236 Transpose a Matrix (1) for each row i take element and store it in element of the transpose. difficulty: where to put (0, 0, 15) ====> (0, 0, 15) (0, 3, 22) ====> (3, 0, 22) (0, 5, -15) ====> (5, 0, -15) (1, 1, 11) ====> (1, 1, 11) Move elements down very often. (2) For all elements in column j, place element in element

CHAPTER 237 void transpose (term a[], term b[]) /* b is set to the transpose of a */ { int n, i, j, currentb; n = a[0].value; /* total number of elements */ b[0].row = a[0].col; /* rows in b = columns in a */ b[0].col = a[0].row; /*columns in b = rows in a */ b[0].value = n; if (n > 0) { /*non zero matrix */ currentb = 1; for (i = 0; i < a[0].col; i++) /* transpose by columns in a */ for( j = 1; j <= n; j++) /* find elements from the current column */ if (a[j].col == i) { /* element is in current column, add it to b */

CHAPTER 238 b[currentb].row = a[j].col; b[currentb].col = a[j].row; b[currentb].value = a[j].value; currentb++ } } } * Program 2.8: Transpose of a sparse matrix (p.77) O(columns*elements)

CHAPTER 239 Discussion: compared with 2-D array representation O(columns*elements) vs. O(columns*rows) elements --> columns * rows when nonsparse O(columns*columns*rows) Problem: Scan the array “columns” times. Solution: Determine the number of elements in each column of the original matrix. ==> Determine the starting positions of each row in the transpose matrix.

CHAPTER 240 [0] [1] [2] [3] [4] [5] row_terms = starting_pos = a[0]668 a[1]0015 a[2]0322 a[3]05-15 a[4]1111 a[5]123 a[6]23-6 a[7]4091 a[8]5228

CHAPTER 241 void fast_transpose(term a[ ], term b[ ]) { /* the transpose of a is placed in b */ int row_terms[MAX_COL], starting_pos[MAX_COL]; int i, j, num_cols = a[0].col, num_terms = a[0].value; b[0].row = num_cols; b[0].col = a[0].row; b[0].value = num_terms; if (num_terms > 0){ /*nonzero matrix*/ for (i = 0; i < num_cols; i++) row_terms[i] = 0; for (i = 1; i <= num_terms; i++) row_term [a[i].col]++ starting_pos[0] = 1; for (i =1; i < num_cols; i++) starting_pos[i]=starting_pos[i-1] +row_terms [i-1];

CHAPTER 242 for (i=1; i <= num_terms, i++) { j = starting_pos[a[i].col]++; b[j].row = a[i].col; b[j].col = a[i].row; b[j].value = a[i].value; } } } *Program 2.9:Fast transpose of a sparse matrix(p.78) Compared with 2-D array representation O(columns+elements) vs. O(columns*rows) elements --> columns * rows O(columns+elements) --> O(columns*rows) Cost: Additional row_terms and starting_pos arrays are required. Let the two arrays row_terms and starting_pos be shared.

CHAPTER 243 spacetime 2D arrayO(rows * cols) TransposeO(elements)O(cols * elmnts) Fast TransposeO(elmnts+MAX _COL) O(cols + elmnts)

CHAPTER 244 *Figure 2.5:Multiplication of two sparse matrices (p.73) Sparse Matrix Multiplication Definition: [D] m*p =[A] m*n * [B] n*p Procedure: Fix a row of A and find all elements in column j of B for j=0, 1, …, p-1. Alternative 1. Scan all of B to find all elements in j. Alternative 2. Compute the transpose of B. (Put all column elements consecutively)

CHAPTER 245 void mmult (term a[ ], term b[ ], term d[ ] ) /* multiply two sparse matrices */ { int i, j, column, totalb = b[].value, totald = 0; int rows_a = a[0].row, cols_a = a[0].col, totala = a[0].value; int cols_b = b[0].col, int row_begin = 1, row = a[1].row, sum =0; int new_b[MAX_TERMS][3]; if (cols_a != b[0].row){ fprintf (stderr, “Incompatible matrices\n”); exit (1); }

CHAPTER 246 fast_transpose(b, new_b); a[totala+1].row = rows_a; new_b[totalb+1].row = cols_b; new_b[totalb+1].col = 0; for (i = 1; i <= totala; ) { column = new_b[1].row; for (j = 1; j <= totalb+1;) { /* mutiply row of a by column of b */ if (a[i].row != row) { storesum(d, &totald, row, column, &sum); i = row_begin; for (; new_b[j].row == column; j++) ; column =new_b[j].row }

CHAPTER 247 else switch (COMPARE (a[i].col, new_b[j].col)) { case -1: /* go to next term in a */ i++; break; case 0: /* add terms, go to next term in a and b */ sum += (a[i++].value * new_b[j++].value); break; case 1: /* advance to next term in b*/ j++ } } /* end of for j <= totalb+1 */ for (; a[i].row == row; i++) ; row_begin = i; row = a[i].row; } /* end of for i <=totala */ d[0].row = rows_a; d[0].col = cols_b; d[0].value = totald; } *Praogram 2.10: Sparse matrix multiplication (p.81)