Structures

advertisement
 Program
data
Data Structure
code
Algorithm

Data vs. Variables
int i = 10;
int i[5]={3,5,7,9,10};

관련 데이터를
structure로 정의
연산 호출시 구조체
변수를 함수 인자로
전달

예) Stack의 표현

// 자료구조 stack 구조체의 정의
typedef int element;
typedef struct {
int top;
element stack[MAX_STACK_SIZE];
} Stack;
// 자료구조 stack과 관련된 연산들을 정의
void push(Stack *s, element item)
{
if( s->top >= (MAX_STACK_SIZE -1)){
stack_full();
return;
}
s->stack[++(s->top)] = item;
}
 Natural
language
 Flow chart
 Pseudo-code or C-like code

and etc

성능 분석 방법 1
◦ 복잡도 분석
 직접 구현하지 않고 수행 시간을 수학적으로 분석
 알고리즘이 수행하는 연산 횟수를 측정하여 비교
 연산의 횟수를 n의 함수로 정의
Time complexity (시간복잡도) 분석
• 소요 수행 시간의 분석
Space complexity (공간복잡도) 분석
• 필요 메모리 공간 크기의 분석

성능 분석 방법 2
 프로그램을 구현하여 실제적 시간 측정
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main( void )
{
clock_t before, after;
double duration;
before= clock();
// 측정 대상 코드.
// ....
after= clock();
duration = (double)(after- before) / CLOCKS_PER_SEC;
printf(“The code takes %f seconds .\n", duration);
}

알고리즘이 수행하는 연산의 횟수를 계산
◦ 산술 연산, 대입 연산, 비교 연산, 이동 연산

연산 수행횟수
◦ 입력 데이터 항목 개수인 n에 대한 함수 T(n)으로 표현
연산횟수 T(n)
입력
데이터
n
• 예제 1.2 배열 값의 합산
statements
steps/
execution
frequency
Total number of steps
float sum(float list[], int m)
0
0
0
{
0
0
0
float tempsum = 0;
1
1
1
int i;
0
0
0
for (i=0; i<n; i++)
1
n+1
n+1
1
n
n
1
1
1
0
0
0
tempsum += list[i];
return tempsum;
}
sum = 2n+3
• 예제 1.4 행렬의 덧셈 계산
statements
Steps/
execution
frequency
Total number
of steps
void add(int a[][MAX_SIZE], … )
0
0
0
{
0
0
0
int i, j;
0
0
0
for(i=0; i<rows; i++)
1
rows+1
rows+1
for(j=0; j<cols; j++)
1
rows*(cols+1)
rows*(cols+1)
1
rows*cols
rows*cols
0
0
0
c[i][j] = a[i][j]+b[i][j];
}
sum = 2rows*cols+2rows+1









O(1) :
O(log n) :
O(n) :
O(nlog n) :
O(n2) :
O(n3) :
O(nk) :
O(2n) :
O(n!) :
◦ 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 0 in C
Variable
list[0]
list[1]
list[2]
list[3]
list[4]

Memory Address
base address = a
a + sizeof(int)
a + 2·sizeof(int)
a + 3·sizeof(int)
a + 4·sizeof(int)
list[i] in C programs
◦ C interprets it as a pointer to an integer or its
value
int *list1;
 pointer variable to an int
int list2[5];
 pointer constant to an int, and five memory locations
for holding integers are reserved
◦ (list2+i) equals &list2[i], and *(list2+i) equals
list2[i] regardless of the type of the array list2

Ex 2.1 [1-dimensional array addressing]
int one[] = {0,1,2,3,4};
◦ write a function that prints out both the address of
the ith element of the array and the value found at
this address
0
one
1
2
one+2
one+1
3
4
one+4
one+3
void print1(int *ptr,int rows) {
printf(“Address Contents\n”);
for(i=0;i<rows;i++)
printf(“%8u %5d\n”,ptr+i,*(ptr+i));
printf(“\n”);
}
◦ One-dimensional array accessed by address
 address of i th element : ptr + i
 obtain the value of the i th value : *(ptr + i)
◦ struct
 structure or record
 mechanism of grouping data
=> data modeling (or data abstraction)
 permits the data to vary in type
 collection of data items where each item is identified
as to its type and name
struct {
char name[10];
int age;
float salary;
} person;

creates a variable whose name is person and has
three fields
1) a name that is a character array
2) an integer value representing the age of the person
3) a float value representing the salary of the individual

use of the . as the structure member
operator
strcpy(person.name, ”james”);
person.age = 10;
person.salary = 35000;
◦ select a particular member of the structure
◦ typedef statement
create our own structure data type
=> user-defined data type
typedef struct {
char name[10];
int age;
float salary;
} human_being;

human_being
◦ the name of the type defined by the structure
definition
human_being person1, person2;
if(strcmp(person1.name, person2.name))
printf(“The two people do not have the same\ name\n”);
else
printf(“The two people have the same\ name\n”);

Assignment
◦ permits structure assignment in ANSI C
person1 = person2;
◦ but, in most earlier versions of C, assignment of
structures is not permitted
strcpy(person1.name,person2.name);
person1.age=person2.age;
person1.salary=person2.salary;

equality or inequality
◦ Cannot be directly checked
◦ Function to check equality of struct
int humans_equal(human_being person1, human_being person2) {
if(strcmp(person1.name,person2.name))
return FALSE;
if(person1.age!=person2.age)
return FALSE;
if(person1.salary!=person2.salary)
return FALSE;
}
return TRUE;

Embedding of a structure within a structure
typedef struct {
int month;
int day;
int year;
} date;
typedef struct{
char name[10];
int age;
float salary;
date dob;
} human_being;
eg) A person born on February 14, 1988
 person1.dob.month = 2;
 person1.dob.day = 14;
 person1.dob.year = 1988;

Unions
◦ similar to a structure, but the fields of a union
must share their memory space
◦ only one field of the union is “active” at any given
time
typedef struct{
enum tag_field {female,male} sex;
union {
int children;
int beard;
} u;
}sex_type;
typedef struct {
char name[10];
int age;
float salary;
date dob;
sex_type sex_info;
} human_being;
human_being person1,person2;
◦ assign values to person1 and person2
person1.sex_info.sex = male;
person1.sex_info.u.beard = FALSE;
and
person2.sex_info.sex = female;
person2.sex_info.u.children = 4;
struct {
int i, j; float a, b;
};
or
struct {
int i; int j; float a; float b;
};

stored in the same way
◦ increasing address locations in the order specified in the
structure definition

size of an object of a struct or union type
◦ the amount of storage necessary to represent the largest
component


one or more of its components is a pointer to itself
usually require dynamic storage management
routines to explicitly obtain and release memory
typedef struct {
char data;
list *link;
} list;
◦ the value of link
 address in memory of an instance of list or null pointer
list item1, item2, item3;
item1.data = ‘a’;
item2.data = ‘b’;
item3.data = ‘c’;
item1.link = item2.link = item3.link = NULL; //initialization
item1
item2
‘a’
‘b’
item3
‘c’

attach these structures together
item1.link=&item2;
item2.link=&item3;
item1
item2
item3
‘a’
‘b’
‘c’

representing matrix by using array
◦ m by n (m rows, n columns)
◦ use two-dimensional array
◦ space complexity
 S(m, n) = m * n
col 0
col 1
col 2
row 0
-27
3
4
row 1
6
82
-2
row 2
109
-64
11
row 3
12
8
9
row 4
48
27
47

Sparse matrix A[6,6]
col 0
col 1
col 2
col 3
col 4
col 5
row 0
15
0
0
22
0
15
row 1
0
11
3
0
0
0
row 2
0
0
0
-6
0
0
row 3
0
0
0
0
0
0
row 4
91
0
0
0
0
0
row 5
0
0
28
0
0
0

common characteristics
◦ most elements are zero’s
◦ inefficient memory utilization

solutions
◦ store only nonzero elements
◦ using the triple <row,col,value>
◦ must know
 the number of rows
 the number of columns
 the number of non-zero elements
#define MAX_TERMS 101
typedef struct {
int col;
int row;
int value;
} term;
term a[MAX_TERMS];
◦
◦
◦
◦
a[0].row: the number of rows
a[0].col: the number of columns
a[0].value: the total number of non-zoros
choose row-major order

sparse matrix as triples

space complexity

independent of the size of rows and columns
a[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
row
col
value
6
0
0
0
1
1
2
4
5
6
0
3
5
1
2
3
0
2
8
15
22
-15
11
3
-6
91
28
◦ S(n, m) = 3 * t, where t : the number of non-zero’s

transpose a matrix
◦ interchange rows and
columns
◦ move a[i][j] to b[j][i]
a[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
row
col
value
6
0
0
0
1
1
2
4
5
6
0
3
5
1
2
3
0
2
8
15
22
-15
11
3
-6
91
28
•Hanyang University
row-major order
b[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
row
col
value
6
0
0
1
2
2
3
3
5
6
0
4
1
1
5
0
2
0
8
15
91
11
3
28
22
-6
-15

Algorithm BAD_TRANS
for each row i
take element <i,j,value>;
store it as element <j,i,value> of the transpose;
end;
◦ problem: data movement

Algorithm TRANS
for all elements in column j
place element <i,j,value> in
element <j,i,value>
end;
◦ problem: unnecessary loop for each column
void transpose(term a[],term b[]) {
}
int n,i,j,currentb;
n = a[0].value; b[0].row = a[0].col;
b[0].col = a[0].row; b[0].value = n;
if(n > 0) {
currentb = 1;
for(i = 0; i < a[0].col; i++) /* col -> row */
for(j = 1; j <= n; j++)
if(a[j].col == i) { /* i번째 col을 찾아냄 */
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}


Time complexity : O(cols·elements)
create better algorithm by using a little more
storage
◦ row_terms
 the number of element in each row
◦ starting_pos
 the starting point of each row
void fast_transpose(term a[],term b[]) {
int row_terms[MAX_COL];
int starting_pos[MAX_COL];
int i,j;
int num_cols = b[0].row = a[0].col;
int num_terms = b[0].value = a[0].value;
b[0].col = a[0].row;
if(num_terms > 0) {
for(i = 0; i < num_cols; i++)
row_terms[i] = 0;
for(i = 1; i <= num_terms; i++)
row_terms[a[i].col]++;
(to be continued)
row
col
value
6
0
0
0
1
1
2
4
5
6
0
3
5
1
2
3
0
2
8
15
22
-15
11
3
-6
91
28
a[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
전치행렬에서 각 행의
값의 개수 계산
starting_pos[0] = 1;
for(i = 1; i < num_cols; i++)
starting_pos[i] = starting_pos[i-1] + row_terms[i-1];
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;
a[0]
b[j].value = a[i].value;
[1]
}
[2]
}
}
[3]
[4]
[5]
[6]
[7]
[8]
row
col
value
6
0
0
0
1
1
2
4
5
6
0
3
5
1
2
3
0
2
8
15
22
-15
11
3
-6
91
28
row_terms =
starting_pos =
[0] [1] [2] [3] [4] [5]
2
1
2
2
0
1
1
3
4
6
8
8
◦ Time complexity : O(cols + elements)
a[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
row
col
value
6
0
0
0
1
1
2
4
5
6
0
3
5
1
2
3
0
2
8
15
22
-15
11
3
-6
91
28

Internal representation of multidimensional arrays
◦ how to state n-dimensional array into 1-dimensional array ?
◦ how to retrieve arbitrary element in
a[upper0][upper1]···[uppern-1]

the number of element in the array
n-1
P upperi
i=0
◦ eg) for a[10][10][10], 10*10*10 = 1000 (units)

represent multidimensional array by
◦ what order ?
 row-major-order
◦ store multidimensional array by rows
a:
···
starting
address
a[0][0]···[0]
a[0][0]···[1]
···
a[0][0]···[0][uppern-1-1]
a[0][0]···[1][0]
···
a[0][1]···[uppern-1-1]
a[0][2]···[0]
···
a[1][0]···[0]
···
···
···
···

how to retrieve
◦ starting-address + offset-value
◦ assume a: starting-address

1-dimensional array a[u0]
a[0]
a[1]
·
·
·
a[u0-1]
:a
:a+1
·
·
·
: a + (u0 - 1)
a[i] = a + i

2-dimensional array a[u0][u1]
j
0
1
·
i
·
·
u0 - 1
0
a
1
a+1
a[i][j] = a + i·u1 + j
···
?
u1 - 1
a + (u 1 -1 )

3-dimensional array a[u0][u1][u2]
a[i][j][k] = a + i·u1·u2 + j·u2 + k
= a + u2[i·u1 + j] + k

general case a[u0][u1]···[un-1]
n-1
a[i0][i1]···[in-1] = a + ij·aj
j=0
where
n-1
aj = uk 0 < j < n-1
k=j+1
an-1 = 1
Download