강의자료6

36
1 4장 ADT Unsorted List( 장장장 장장 장)

Upload: young-wook-kim

Post on 23-Jun-2015

187 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 강의자료6

1

4 장 ADT Unsorted List( 비정렬 리스트 )

Page 2: 강의자료6

2

List Definitions

Logical Properties of (Linear) Lists An ordered collection of homogeneous elements ( 순서가 있는 동형의

원소들의 모임 ) Operations create the list ( 리스트 생성 ) determine whether the list is empty ( 리스트가 비어있는지를 결정 ) find the size (length) of the list ( 리스트의 길이 구하기 ) find the index of the element ( 원소의 위치 구하기 ) retrieve the element at a particular index ( 특정한 위치에 있은 원소 검

색 ) change the element at a particular index to a different value ( 특정한

위치의 원소를 다른 값을 변경 ) insert an element at a particular index ( 특정한 위치에 원소를 삽입 ) remove an element at a particular index ( 특정한 위치의 원소를 삭제 )

Length ( 길이 ) The number of items in a list; the length can vary over time.

Page 3: 강의자료6

3

List Definitions

Logical Properties – another definition ( 리스트의 다른 정의로서 교안에서 사용하는 정의임 )

A collection of homogeneous elements with linear relationship between elements ( 순서 관계가 있는 동형의 원소들의 모임 )

operations: create the list ( 리스트 생성 ) determine whether the list is empty ( 리스트가 비어있는지를 결정 ) find the size (length) of the list ( 리스트의 길이 구하기 )

retrieve an item with given key value ( 특정한 키의 원소 검색 ) insert an item ( 원소의 삽입 )

delete an item with given key value ( 특정한 키의 원소 삭제 )

Key ( 키 ) The attributes that are used to determine the logical order of the list. 리스트의 논리적 순서를 정하는데 사용되는 속성들 Length ( 길이 ) The number of items in a list; the length can vary over time.

Page 4: 강의자료6

4

List Definitions

Unsorted list ( 비정렬 리스트 ) A list in which data items are placed in no particular order;

the only relationship between data elements is the list

predecessor and successor relationships.

(no semantic relationship between an item and its successor or predecessor)

Sorted list ( 정렬 리스트 ) A list that is sorted by the value in the key;

there is a semantic relationship among the keys of the items in the list. Key: Attributes used to determine the logical order of the list 예 : Student ID (or student name) as the key for student record data item

Page 5: 강의자료6

5

Abstract Data Type (ADT)

A data type whose properties (domain and operations) are specified independently of any particular implementation.

Not concerned with implementation details now…

What operations we should provide for ADT Unsorted List?

Page 6: 강의자료6

4 Basic Kinds of ADT Operations

Constructor: creates a new instance (object) of an ADT.

Transformer: changes the state of one or more of the data values of an instance.

Observer: allows us to observe the state of one or more of the data

values of an instance without changing them.

Iterator: allows us to process all the components in a data structure sequentially.

6

Page 7: 강의자료6

ADT Unsorted List Operations

Transformers MakeEmpty InsertItem DeleteItem

Observers IsFull IsEmpty LengthIs RetrieveItem

Iterators ResetList GetNextItem

change state

observe state

process all

7

Page 8: 강의자료6

ADT 와 C++ 클래스

C++ 은 클래스 기법을 사용하여 ADT를 표현

C++ 클래스의 구성(1) 클래스 이름(2) 데이타 멤버(3) 멤버 함수 : 연산

8

Page 9: 강의자료6

// SPECIFICATION FILE ( unsorted.h )

class UnsortedType // declares a class data type{public : // 9 public member functions

void UnsortedType ( ) ;bool IsEmpty ( ) const ; bool IsFull ( ) const ; int LengthIs ( ) const ; // returns length of listvoid RetrieveItem ( ItemType& item, bool& found ) ;void InsertItem ( ItemType item ) ; void DeleteItem ( ItemType item ) ; void ResetList ( );void GetNextItem ( ItemType& item ) ;

….} ; struct ItemType

{ …. KeyType key; …};

Page 10: 강의자료6

10

자료의 표현

연산 ( 멤버함수 ) 의 구현

자료의 표현방법에 따라 멤버함수의 구현이 달라진다 .

자료를 어떻게 표현하느냐에 따라 멤버함수의 효율성( 수행시간 ) 을 결정

구현 (IMPLEMENTATION)

Page 11: 강의자료6

두 가지 구현방법

1) 배열로의 구현 2) 연결구조로의 구현

ADT ADT Unsorted List 구현

Public declarations are the same for different implementations; only private data changes

Page 12: 강의자료6

// SPECIFICATION FILE ( unsorted.h )

class UnsortedType // declares a class data type{public : // 8 public member functions ……

private : // 3 private data members// 리스트를 배열로 표현

int length ; ItemType info[MAX_ITEMS] ; // MAX_ITEMS 은 상수임 int currentPos ;

} ; struct ItemType{ …. KeyType key; …};

ADT ADT Unsorted List 배열 구현

Page 13: 강의자료6

배열 구현

13

• The array( 배열 ) ends at the slot with index MAX_ITEMS – 1

• The list ends in the slot with index length - 1

Page 14: 강의자료6

14

Class Constructor

A special member function of a class that is implicitly invoked when a class object is defined.

( 객체가 정의될 때 내부적으로 호출되는 특수한 멤버함수 )

Page 15: 강의자료6

15

Class Constructor Rules

1 A constructor cannot return a function value, and has no return value type. ( 결과값이 없음 ; 반환 형이 없음 )

2 A class may have several constructors. The compiler chooses the appropriate constructor by the number and types of parameters used. ( 생성자가 여러 개일 수 있음 – 사용되는 인자의 수와 형에 맞는 생성자를 선택 )

3 Constructor parameters are placed in a parameter list in the declaration of the class object.

4 The parameterless constructor is the default constructor.

( 인자가 없는 생성자 : 디폴트 생성자 ) 5 If a class has at least one constructor, and an array of class objects

is declared, then one of the constructors must be the default constructor, which is invoked for each element in the array.

Page 16: 강의자료6

16

Class Interface Diagram

UnsortedType class

IsFull

LengthIs

ResetList

DeleteItem

InsertItem

UnsortedType

RetrieveItem

GetNextItem

Private data:

length

info [ 0 ] [ 1 ] [ 2 ]

[MAX_ITEMS-1]

currentPos

IsEmpty

Page 17: 강의자료6

17

생성자 구현

// IMPLEMENTATION FILE ARRAY-BASED LIST ( unsorted.cpp )void UnsortedType::UnsortedType ( ) // Pre: None.// Post: List is empty.{

length = 0 ;}

LengthIs 구현int UnsortedType::LengthIs ( ) const// Pre: List has been initialized.// Post: Function value == ( number of elements in list ).{

return length ;} 17

멤버 함수 구현

Page 18: 강의자료6

18

Is the list full ? //pre: List has been initialized//post: function value = (list is full)bool UnsortedType::IsFull() const{ return (length == MAX_ITEM);}

Is it empty ? //pre: List has been initialized//post: function value = (list is empty)bool UnsortedType:: IsEmpty() const{ return (length == 0);}

observers

Page 19: 강의자료6

InsertItem

19

length 3

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] .

. .

[MAX_ITEMS-1]

If the list is unsorted, where should “Hsing” go?

insert("Hsing");

Page 20: 강의자료6

InsertItem

20

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

.

[MAX_ITEMS-1]

That was easy!Can you code it?

Page 21: 강의자료6

21

void UnsortedType::InsertItem ( ItemType item )// Pre: List has been initialized. List is not full. item is not in

list.// Post: item is in the list.{

info[length] = item ;length++ ;

}

Page 22: 강의자료6

void UnsortedType::RetrieveItem ( ItemType& item, bool& found ) // Pre: Key member of item is initialized.// Post: If found, item’s key matches an element’s key in the list and a copy of that element// has been stored in item; otherwise, item is unchanged.{ bool moreToSearch ; int location = 0 ;

found = false ; moreToSearch = ( location < length ) ; while ( moreToSearch && !found ) { if (item.key == info[location].key) { found = true; item = info[location]; } else { location++; moreToSearch = (location < length); } }}

Page 23: 강의자료6

23

void UnsortedType::RetrieveItem ( ItemType& item, bool& found ) // Pre: Key member of item is initialized.// Post: If found, item’s key matches an element’s key in the list and a copy of

that element// has been stored in item; otherwise, item is unchanged.{ int location = 0 ;

found = false ; while ( location < length && !found ) { if (item.key == info[location].key) { found = true; item = info[location]; } else location++; }}

Page 24: 강의자료6

DeleteItem: before the operation

24

location: 0 length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Delete Bradley

Page 25: 강의자료6

DeleteItem: Finding the item

25

location: 1

Key Bradley hasbeen matched

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Page 26: 강의자료6

DeleteItem: after the operation

26

location: 1

length 3

info [ 0 ] Maxwell

[ 1 ] Hsing

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1] * Copy last list element to where key “Bradley” was before* length has been decremented

Page 27: 강의자료6

27

void UnsortedType::DeleteItem ( ItemType item ) // Pre: item’s key has been initialized.// An element in the list has a key that matches item’s.// Post: No element in the list has a key that matches item’s.{ int location = 0 ; while (item.key != info[location].key) location++;

// move last element into position where item was located info [location] = info [length - 1 ] ; length-- ;}

Page 28: 강의자료6

28

// Pre: N/A

// Post: the list is empty

bool UnsortedType::MakeEmpty()

{

length = 0;

} We do not have to do anything to the array that

holds the list items to make a list empty.

Page 29: 강의자료6

29

void UnsortedType::ResetList ( ) // Pre: List has been initialized.// Post: Current position is prior to first element in list.{

currentPos = -1 ;}

void UnsortedType::GetNextItem ( ItemType& item ) // Pre: List has been initialized. Current position is defined.// Element at current position is not last in list.// Post: Current position is updated to next position.// item is a copy of element at current position.{

currentPos++ ;item = info [currentPos] ;

}

Iterators

Page 30: 강의자료6

Application Level

30

How to use the List implemented? PrintList(UnsortedType&) CreateFromFile(ifstream &, UnsortedType&)

Users do not need to know how the list is implemented.

Page 31: 강의자료6

Application Level

31

// Pre: list has been initialized. //// Post: Each component in list has been written. // void PrintList(UnsortedType & list){ int length; ItemType item;

list.ResetList( ); length = list.GetLength( ); for (int counter = 1; counter <= length; counter++) { list.GetNextItem(item); item.Print(); }}

Page 32: 강의자료6

Order of Magnitude of a Function

The order of magnitude, or Big-O notation, of a function expresses the computing time of a problem as the term in a function that increases most rapidly relative to the size of a problem.

수행시간의 Big-O 표기 : 수행시간에 대한 함수 표기방법으로 문제의 크기와 관련하여 수행시간을 가장 빠르게 증가시키는 함수의 항으로 나타냄

O : 함수를 ( 증가속도에 따라 ) 분류하는 방법

32

Page 33: 강의자료6

Names of Orders of Magnitude

O(1) bounded (by a constant) time // 상수시간

O(log2N) logarithmic time

O(N) linear time

O(N*log2N) N*log2N time

O(N2) quadratic time

O( 2N ) exponential time 33

Page 34: 강의자료6

The Story of Big O

34

• Algorithm running time (work) as a function of N (size of the input)

•F(N)=N4+100N2+10N+50

• Order of magnitude of F(N), Big-O notation

• an approximation of F(N) with the term in the function that increases fastest with N

• For above F(N), which part increases fastest when N increases ?

• N4, for large N, N4 is much larger than 100N2, 10N

• F(N) is of order N4, or is O(N4)

Page 35: 강의자료6

Algorithm Growth Rates

35

Figure Time requirements as a function of the problem size n

• Algorithm A requires time proportional to n2

• Algorithm B requires time proportional to n• A is more time efficient than B

Page 36: 강의자료6

Big-O Comparison of List Operations

OPERATION UnsortedList 의 배열구현

RetrieveItem O(N)

InsertItemFind O(1)Put O(1)Combined O(1)

DeleteItemFind O(N)Put O(1) swapCombined O(N)