이산수학 (discrete mathematics) 2.1 알고리즘 (algorithms) 2006 년 봄학기 문양세...

31
이이이이 (Discrete Mathematics) 2.1 이이이이 (Algorithms) 2006 2006 이 이이이 이 이이이 이이이 이이이 이이이이이 이이이이이이 이이이이이 이이이이이이

Upload: ethelbert-wood

Post on 17-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

이산수학 (Discrete Mathematics)

2.1 알고리즘 (Algorithms)

20062006 년 봄학기년 봄학기

문양세문양세강원대학교 컴퓨터과학과강원대학교 컴퓨터과학과

Page 2: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 2Discrete Mathematicsby Yang-Sae Moon

Overview of Chapter 2Overview of Chapter 2

$2.1 Algorithms (formal procedures)

$2.2 Growth of Functions

$2.3 Complexity of Algorithms

$2.4 The Integers & Division

$2.5 Integers & Algorithms

$2.7 Matrices

2.1 Algorithms

Page 3: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 3Discrete Mathematicsby Yang-Sae Moon

AlgorithmsAlgorithms

The foundation of computer programming.( 컴퓨터 프로그래밍의 기초 / 기반이다 .)

Most generally, an algorithm just means a definite procedure for performing some sort of task.( 알고리즘은 주어진 일을 수행하기 위한 정의된 절차를 의미한다 .)

A computer program is simply a description of an algorithm in a language precise enough for a computer to understand.( 컴퓨터 프로그램이란 정의된 알고리즘을 컴퓨터가 이해할 수 있는 언어로 정확하게 기술한 것에 불과하다 .)

We say that a program implements (or “is an implementation of”) its algorithm.( 프로그램은 알고리즘을 “구현한 것이다”라고 이야기한다 .)

2.1 Algorithms

Page 4: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 4Discrete Mathematicsby Yang-Sae Moon

Programming LanguagesProgramming Languages

Some common programming languages:

• Newer: Java, C, C++, Visual Basic, JavaScript, Perl, Tcl, Pascal

• Older: Fortran, Cobol, Lisp, Basic

• Assembly languages, for low-level coding.

In this class we will use an informal, Pascal-like “pseudo-code” language. ( 아마 , 알고리즘 시간에도 … )

You should know at least 1 real language!

2.1 Algorithms

Page 5: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 5Discrete Mathematicsby Yang-Sae Moon

Algorithm Example (in English)Algorithm Example (in English)

Task: Given a sequence {ai}=a1,…,an, aiN, say what its largest element is. ( 주어진 sequence 에서 가장 큰 수는 ?)

Algorithm in English

• Set the value of a temporary variable v to a1’s value.

• Look at the next element ai in the sequence.

• If ai>v, then re-assign v to the number ai.

• Repeat previous 2 steps until there are no more elements in the sequence, & return v.

2.1 Algorithms

Page 6: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 6Discrete Mathematicsby Yang-Sae Moon

Executing an AlgorithmExecuting an Algorithm

When you start up a piece of software, we say the program or its algorithm are being run or executed by the computer.( 소프트웨어를 시작할 때 , 우리는 프로그램 혹은 알고리즘을 실행한다 ( 혹은 돌린다 ) 라고 이야기한다 .)

Given a description of an algorithm, you can also execute it by hand(?), by working through all of its steps on paper.( 알고리즘이 있으면 , 종이에 손으로 써 가면서 이를 수행할 수도 있다 .)

Before ~WWII, “computer” meant a person whose job was to run algorithms!(2 차 대전 이전에 , 컴퓨터는 알고리즘을 수행하는 사람을 의미했다 !)

2.1 Algorithms

Page 7: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 7Discrete Mathematicsby Yang-Sae Moon

Execute the Execute the MaxMax Algorithm Algorithm

Let {ai}=7,12,3,15,8. Find its maximum… by hand.

Set v = a1 = 7.

Look at next element: a2 = 12.

Is a2>v? Yes, so change v to 12.

Look at next element: a2 = 3.

Is 3>12? No, leave v alone….

Is 15>12? Yes, v=15…

2.1 Algorithms

Page 8: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 8Discrete Mathematicsby Yang-Sae Moon

Algorithm Characteristics (Algorithm Characteristics ( 알고리즘의 특성알고리즘의 특성 ) (1/2)) (1/2)

Some important features of algorithms:

Input( 입력 ): Information or data that comes in.

Output( 출력 ): Information or data that goes out.

Definiteness( 명확성 ): Precisely defined.

( 각 단계는 명확하게 정의되어야 한다 .)

Correctness( 정확성 ): Outputs correctly relate to inputs.

( 입력 값의 각 집합에 대해서 정확한 출력 값을 만들어야 한다 .)

Finiteness( 유한성 ): Won’t take forever to describe or run.

2.1 Algorithms

Page 9: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 9Discrete Mathematicsby Yang-Sae Moon

Algorithm Characteristics (Algorithm Characteristics ( 알고리즘의 특성알고리즘의 특성 ) (2/2)) (2/2)

Some important features of algorithms ( 계속 ):

Effectiveness( 효율성 ): Individual steps are all do-able.

( 각 단계는 유한한 양의 시간에 수행되어야 한다 .)

Generality( 일반성 ): Works for many possible inputs.

( 특정한 입력이 아닌 모든 가능한 입력에 대해서 동작하여야 한다 .)

2.1 Algorithms

Page 10: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 10Discrete Mathematicsby Yang-Sae Moon

Pseudocode Language (in $A2)Pseudocode Language (in $A2)

procedurename(argument: type)

variable := expressioninformal statementbegin statements end

{comment}if condition then

statement [else statement]

for variable := initial value to final value statement

while condition statement

procname(arguments) Not defined in book:return expression

2.1 Algorithms

Page 11: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 11Discrete Mathematicsby Yang-Sae Moon

procedureprocedure procnameprocname((argarg: : typetype))

Declares that the following text defines

• a procedure named procname that takes

• inputs (arguments) named arg which are

• data objects of the type type.

Example:

procedure maximum(L: list of integers)[statements defining maximum…]

2.1 Algorithms

Page 12: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 12Discrete Mathematicsby Yang-Sae Moon

variablevariable :=:= expressionexpression

An assignment statement evaluates the expression, then reassigns the variable to the value that results.• Example: v := 3x+7 (If x is 2, changes v to 13.)

In pseudocode, the expression might be informal:• x := the largest integer in the list L

2.1 Algorithms

Page 13: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 13Discrete Mathematicsby Yang-Sae Moon

Informal StatementInformal Statement

Sometimes we may write a informal statement, if the meani

ng is still clear and precise: “swap x and y.”

Keep in mind that real programming languages never allow t

his. ( 궁극적으로는 알고리즘을 쓰고 이를 구현해야 한다 .)

When we ask for an algorithm to do so-and-so, writing “Do s

o-and-so” isn’t enough!

(“x 를 찾는 알고리즘을 기술하라”했는데 , “Find abc” 라 하는 것은 충분치 않다 !)

• Break down algorithm into detailed steps.

2.1 Algorithms

Page 14: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 14Discrete Mathematicsby Yang-Sae Moon

beginbegin statementsstatements endend2.1 Algorithms

Groups a sequence of statements together:

begin statement 1 statement 2 … statement n end

Allows sequence to be used like a single statement.Might be used:• After a procedure

declaration.• In an if statement

after then or else.• In the body of a for or while loop.

Page 15: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 15Discrete Mathematicsby Yang-Sae Moon

{ { commentcomment }}

Not executed (does nothing).

Natural-language text explaining some aspect of the procedure to human readers. (Reader 의 이해 도모 )

Also called a remark in some real programming languages.

Example:

• {Note that v is the largest integer seen so far.}

2.1 Algorithms

Page 16: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 16Discrete Mathematicsby Yang-Sae Moon

IfIf conditioncondition thenthen statementstatement

Evaluate the propositional expression condition.

If the resulting truth value is true, then execute the statement; otherwise, just skip on ahead to the next statement. (조건이 true 일 때만 문장을 수행한다 .)

Variant: if cond then stmt1 else stmt2

Like before, but iff truth value is false, executes stmt2.

2.1 Algorithms

Page 17: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 17Discrete Mathematicsby Yang-Sae Moon

whilewhile commentcomment statementstatement (1/2) (1/2)

Evaluate the propositional expression condition.

If the resulting value is true, then execute

statement.

Continue repeating the above two actions over and

over until finally the condition evaluates to false;

then go on to the next statement.( 조건이 true 인 한 문장을 반복하여 수행한다 .)

2.1 Algorithms

Page 18: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 18Discrete Mathematicsby Yang-Sae Moon

whilewhile commentcomment statementstatement (2/2) (2/2)

Also equivalent to infinite nested ifs, like so:(if 를 무한히 써서 구현할 수도 있다… . 설마 ~)

2.1 Algorithms

if conditionbegin

statement if condition

begin statement …(continue infinite nested if’s)

endend

Page 19: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 19Discrete Mathematicsby Yang-Sae Moon

forfor varvar := initial := initial toto final final stmtstmt

Initial is an integer expression.

Final is another integer expression.

Repeatedly execute stmt, first with variable var := initial, then with var := initial+1, then with var := initial+2, etc., then finally with var := final.

2.1 Algorithms

What happens if stmt changes the value that initial or final evaluates to?

ForFor can be exactly defined in can be exactly defined in terms of terms of while,while, like so: like so:

beginvar := initialwhile var final

beginstmtvar := var + 1

endend

Page 20: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 20Discrete Mathematicsby Yang-Sae Moon

procedureprocedure((argumentargument))

A procedure call statement invokes the named procedure, giving it as its input the value of the argument expression.

Various real programming languages refer to procedures as

• functions (since the procedure call notation works similarly to function application f(x)), or as

• subroutines, subprograms, or methods.

2.1 Algorithms

Page 21: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 21Discrete Mathematicsby Yang-Sae Moon

Max Procedure in PseudocodeMax Procedure in Pseudocode

Rewrite “finding maximum number” in pseudocode.

2.1 Algorithms

procedure max(a1, a2, …, an: integers)

v := a1 {largest element so far}

for i := 2 to n {go thru rest of elems}

if ai > v then v := ai {found bigger?}

{at this point v’s value is the same as the largest

integer in the list}

return v

Page 22: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 22Discrete Mathematicsby Yang-Sae Moon

Inventing an AlgorithmInventing an Algorithm

Requires a lot of creativity and intuition.

• Like writing proofs.

We can’t give you an algorithm for inventing algorithms.

• Just look at lots of examples… [ 많은 예를 보세요… ]

• And practice (preferably, on a computer) [ 연습을 많이 하세요… ]

• And look at more examples… [ 좀 더 많은 예를 보세요… ]

• And practice some more… etc., etc. [ 좀 더 많은 연습을 하세요… ]

2.1 Algorithms

Page 23: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 23Discrete Mathematicsby Yang-Sae Moon

Searching Algorithm (Searching Algorithm ( 탐색 알고리즘탐색 알고리즘 ))

Problem of searching an ordered list.( 정렬된 리스트에서 주어진 값을 찾아내는 검색을 수행하는 문제 )

• Given a list L of n elements that are sorted into a definite order (e.g., numeric, alphabetical),

• And given a particular element x,

• Determine whether x appears in the list,

• and if so, return its index (position) in the list.

Problem occurs often in many contexts.( 여러 분이 Programming 을 하는 한 수십 번 이상 마주치는 문제임 !)

Let’s find an efficient algorithm!

2.1 Algorithms

Page 24: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 24Discrete Mathematicsby Yang-Sae Moon

Linear Search (Linear Search ( 선형 탐색선형 탐색 ))

리스트의 첫 번째 원소부터 차례대로 검색하는 방법

예 : Find ‘12’ in {3, 6, 9, 12, 15, 18, 21, 24}

2.1 Algorithms

procedure linear search(x: integer, a1, a2, …, an: distinct integers)

i := 1while (i n x ai)

i := i + 1if i n then location := i

else location := 0return location {index or 0 if not found}

Linear search 는 ordered list( 정렬된 상태 ) 뿐 아니라 unordered list( 정렬되지 않은 상태 ) 에서도 바르게 동작한다 .

Page 25: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 25Discrete Mathematicsby Yang-Sae Moon

Binary Search (Binary Search ( 이진 탐색이진 탐색 ) (1/2)) (1/2)

Basic idea: On each step, look at the middle element of the remaining list to eliminate half of it.

( 리스트의 중간에 위치한 값과 비교하여 , 작은 값들을 가지는 리스트 혹은 큰 값들을 가지는 리스트 중에서 한쪽 부분에 대해서만 검사를 진행한다 .)

예 : Find ‘18’ in { 3, 6, 9, 12, 15, 18, 21, 24 }

2.1 Algorithms

<x >x<x<x

Page 26: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 26Discrete Mathematicsby Yang-Sae Moon

Binary Search (Binary Search ( 이진 탐색이진 탐색 ) (2/2)) (2/2)2.1 Algorithms

procedure binary search(x:integer, a1, a2, …, an: distinct integers)

i := 1 {left endpoint of search interval}j := n {right endpoint of search interval}while i<j begin {while interval has >1 item}

m := (i+j)/2 {midpoint}

if x>am then i := m+1 else j := m

end

if x = ai then location := i else location := 0

return location

Binary search 는 ordered list( 정렬된 상태 ) 에서만 바르게 동작할 뿐 unordered list( 정렬되지 않은 상태 ) 에서는 바르게 동작하지 않는다 .

Page 27: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 27Discrete Mathematicsby Yang-Sae Moon

Sorting Algorithm (Sorting Algorithm ( 정렬 알고리즘정렬 알고리즘 ))2.1 Algorithms

Sorting is a common operation in many applications.(Programming 을 하는 한 Search 다음으로 많이 마주치는 문제임 !)

• E.g. spreadsheets and databases

It is also widely used as a subroutine in other data-processing algorithms.

Two sorting algorithms shown in textbook:• Bubble sort

• Insertion sort

There are more than 15 different sorting algorithms!(“The Art of Computer Programming” by Donald Knuth.)

However, these are not very efficient, and you should not use them on large data sets!

Page 28: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 28Discrete Mathematicsby Yang-Sae Moon

Bubble Sort – ExampleBubble Sort – Example2.1 Algorithms

Sort L = {3, 2, 4, 1, 5}

32415

23415

23415

23145

23145

23145

21345

21345

12345

12345

2nd pass1st pass

3rd pass 4th pass

Page 29: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 29Discrete Mathematicsby Yang-Sae Moon

Bubble Sort – AlgorithmBubble Sort – Algorithm2.1 Algorithms

procedure bubble sort(a1, a2, …, an: real numbers with n 2)

for i := 1 to n - 1

for j := 1 to n - i

if aj > aj+1 then interchange aj and aj+1

{a1, a2, …, an is in increasing order.}

Page 30: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 30Discrete Mathematicsby Yang-Sae Moon

Insertion SortInsertion Sort2.1 Algorithms

procedure binary sort(a1, a2, …, an: real numbers with n 2) for j := 2 to n

i := 1while aj > ai {find a proper position of aj}

i := i + 1 m := aj

for k := 0 to j – i – 1 {insert aj into the proper position} aj-k := aj-k-1

aj := m {a1, a2, …, an is in increasing order.}

32415

23415

23415

23415

23415

12345

12345

12345

Page 31: 이산수학 (Discrete Mathematics) 2.1 알고리즘 (Algorithms) 2006 년 봄학기 문양세 강원대학교 컴퓨터과학과

Page 31Discrete Mathematicsby Yang-Sae Moon

Greedy AlgorithmGreedy Algorithm2.1 Algorithms

최적의 알고리즘 (optimal algorithm) 을 찾기가 어렵다 ?

알고리즘의 각 단계에서 최선을 선택을 수행하는 Greedy algorithm 을 사용할 수 있다 .

• Greedy algorithm 은 최적일 수도 있다 .

• 최적임을 보이기 위해서는 증명이 필요하고 , 최적이 아님을 보이기 위해서는 반례(counterexample) 를 든다 .

예제 6

• 25, 10, 5, 1 센트의 동전이 있을 때 , 동전의 수를 최소화하면서 67 센트의 거스름돈을 만들어라 .

− 25 센트 동전을 선택한다 . (42 센트 남음 )− 25 센트 동전을 선택한다 . (17 센트 남음 )− 10 센트 동전을 선택한다 . (7 센트 남음 )− 5 센트 동전을 선택한다 . (2 센트 남음 )− 1 센트 동전을 선택한다 . (1 센트 남음 )− 1 센트 동전을 선택한다 . (1 센트 남음 )