introduction to complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי...

86
Introduction to Complexity

Upload: gwenda-horton

Post on 17-Jan-2018

234 views

Category:

Documents


0 download

DESCRIPTION

אלגוריתם א' אם A גדול מ-B, ו- B גדול מ-C, אז הדפס A,B,C אם A גדול מ-C, ו- C גדול מ-B, אז הדפס A,C,B אם B גדול מ-A, ו-A גדול מ-C, אז הדפס B,A,C אם B גדול מ-C, ו-C גדול מ-A, אז הדפס B,C,A אם C גדול מ-A, ו-A גדול מ-B, אז הדפס C,A,B אם C גדול מ-B, ו-B גדול מ-A, אז הדפס C,B,A

TRANSCRIPT

Page 1: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Introduction to Complexity

Page 2: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

בעיה פשוטה במיוחד

סדר שלושה מספרים לפי סדר מונוטוני עולה

יש למישהו רעיון?

Page 3: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתם א' אםA-גדול מ B -ו ,B-גדול מ C אז הדפס ,A,B,C אםA-גדול מ C -ו ,C-גדול מ B אז הדפס ,A,C,B אםB-גדול מ A-ו ,A-גדול מ C אז הדפס ,B,A,C אםB-גדול מ C-ו ,C-גדול מ A אז הדפס ,B,C,A אםC-גדול מ A-ו ,A-גדול מ B אז הדפס ,C,A,B אםC-גדול מ B-ו ,B-גדול מ A אז הדפס ,C,B,A

Page 4: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתם ב' אםA-גדול מ B

אםB-גדול מ C הדפס ,A,B,C אחרת, אםA-גדול מ C הדפס A,C,B אחרת, הדפסC,A,B

אחרת אםC-גדול מ B הדפס ,C,B,A אחרת, אםA-גדול מ C הדפס B,A,C אחרת, הדפסB,C,A

Page 5: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

איזה פתרון יותר טוב?

?נריץ בראש על כמה מספרים ונבדוק שעובד?נראה בכמה משתנים כל אלגוריתם משתמש?ננסה על מספר מחשבים

-יוסי יבדוק את אלגוריתם א' על הMacintoshשלו -יונית תבדוק את אלגוריתם ב' על הPentiumבמעבדה

Page 6: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

השוואת אלגוריתמיםהיחידה הבסיסית )במקרה זה(: השוואה בין שני מספריםככל שיש יותר השוואות, לוקח יותר זמן להגיע לתשובה

Page 7: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתם א' אםA-גדול מ B -ו ,B-גדול מ C אז הדפס ,A,B,C אםA-גדול מ C -ו ,C-גדול מ B אז הדפס ,A,C,B אםB-גדול מ A-ו ,A-גדול מ C אז הדפס ,B,A,C אםB-גדול מ C-ו ,C-גדול מ A אז הדפס ,B,C,A אםC-גדול מ A-ו ,A-גדול מ B אז הדפס ,C,A,B אםC-גדול מ B-ו ,B-גדול מ A אז הדפס ,C,B,A

Page 8: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

השוואת אלגוריתמיםהיחידה הבסיסית )במקרה זה(: השוואה בין שני מספריםככל שיש יותר השוואות, לוקח יותר זמן להגיע לתשובה

אלגוריתם א': 10 במקרה הרע: 2במקרה הטוב:

!(6 )לא 5בממוצע:

Page 9: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתם ב' אםA-גדול מ B

אםB-גדול מ C הדפס ,A,B,C אחרת, אםA-גדול מ C הדפס A,C,B אחרת, הדפסC,A,B

אחרת אםC-גדול מ B הדפס ,C,B,A אחרת, אםA-גדול מ C הדפס B,A,C אחרת, הדפסB,C,A

Page 10: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

השוואת אלגוריתמיםהיחידה הבסיסית )במקרה זה(: השוואה בין שני מספריםככל שיש יותר השוואות, לוקח יותר זמן להגיע לתשובה

אלגוריתם א': 10 במקרה הרע: 2במקרה הטוב:

!(6 )לא 5בממוצע:

אלגוריתם ב':3 במקרה הרע: 2במקרה הטוב:

2.666בממוצע:

Page 11: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתמים כבסיס לתוכנה?מהו אלגוריתם

סידרה סופית של פעולות לביצוע הפותרות בעיה אלגוריתמית?מהי בעיה אלגוריתמית

הגדרת אוסף קלטים חוקיים)הגדרת פלטים רצויים )פונקציה של הקלטיםלא כל הבעיות האלגוריתמיות ניתנות לפיתרון

אלגוריתם מתאר בבהירות תהליך:הופך קלט חוקי לפלט חוקי ומסיים.

Page 12: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

אלגוריתמים?

ברמזור הבא פני ימינה ואז תמשיך שלושה-ארבעה ק"מ.ברמזור הבא פנה ימינה ואז אתה כבר באזור. תשאל שם .קח שלוש כפיות סוכר. ערבב בתוך כוס מים רותחים.מיין את רשימת המספרים. הדפס את האיבר הראשון:בצע

.5 ל-3בחר רנדומלית מספר בין 1.

1"יש", אחרת חזור ל- , הדפס4אם המספר גדול מ-2.

1חזור ל-3.

Page 13: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

למה צריך אלגוריתמים?אם אוסף הקלטים החוקי הוא אינסופי או גדול מאד

כל הרשימות האפשריות של מספרים השלמיםאם אוסף הפלטים החוקי הוא אינסופי או גדול מאד

:מליון הספרות הראשונות של פאי300לדוגמא

!אחרת, אפשר פשוט להשתמש בטבלה

Page 14: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

מדידת איכות של תוכנה:איכות של תוכנית נמדדת במדדים שונים

קלות התחזוקה של התוכניתמודולריות ואפשרות השימוש בתוכנית למטרות שונותיעילות התוכנית בזמן ריצה ובשימוש בזיכרון

בקורס זה אנו מתמקדים במדדי יעילות( סיבוכיותהמטרה: ניתוח יעילות של אלגוריתמים)

לא להיות תלויים במדידות אמפיריות שלא מאפשרות השוואה שניות על מחשב פנטיום עם 1.3כגון: "התוכנה סיימה בתוך

MB256"זיכרון פנימי

Page 15: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

(Complexity)ניתוח סיבוכיות

זיכרון וזמן ריצהWorst CaseAverage Case

Best Case:פונקציה של

גודל הקלט בביטים, במספר המרכיבים )לדוגמאבמיון(, ...

מודל המחשוב: מעבד מרכזי, זיכרון מרכזי מסוגRAM....,מחיר פעולה בסיסית: השוואה, חישוב אריתמטי

Page 16: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

חישוב יעיל-נסמן את זמן הריצה של אלגוריתם בT)n( ואת הזיכרון

)S)nהנדרש ב-Nהינו גודל הקלט

לדוגמא: בעיית חיפוש מספר במערך קלט: מערךA בגודל nמספר ; המכיל מספרים k לחיפוש פלט: אםk-נמצא במקום ה i החזר ,i אחרת החזר ,Nil.

Page 17: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

.1חיפוש איבר במערך For i1 to n2. If A[i] = k 3. return i4. return Nil

Best Case: When k = A[1], search is over as soon as begun T)n( = C )C is a constant(

C = time to do i1 + time to compare to n + time to compare to k + …

Page 18: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

.1חיפוש איבר במערך For i1 to n2. If A[i] = k 3. return i4. return Nil

Worst Case: When k not in A[], search goes through entire list T)n( = C+B+B+B+…. +D )C,B,D constants(

n times = C+n*B+D

Page 19: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

חיפוש איבר במערך1. For i1 to n2. If A[i] = k 3. return i4. return Nil

Average Case: Let Ti be the time it takes to find k when in A[i] Suppose k can be in any place i, or outside of A[]

With uniform distribution T)n( = )T1+T2+T3+ …. Tn( / n =

22(1)

2(1)11

11

CCnn

nCnnnnCCi

nT

n

n

i

n

ii

Page 20: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

פונקציות אסימפטוטיות עכשיו יש לנו זמני ריצה נתונים בקבועיםC,B,Dהקבועים ישתנו בין מחשבים אז איך נוכל להשוות בין אלגוריתמים בעלי קבועים שונים או

שונות?)T)nפונקציות :לצורך כך אנו משתמשים בפונקציות אסימפטוטיות

O או-גדול( Big-O) אומגה-גדול(Big-Omega) טתה- גדול(Big-Theta)

פונקציות אסימפטוטיות מאפיינות סדר גודל – התנהגות הפונקציהכשגודל הקלט עולה

Page 21: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big – O: חסם עליון

Definition: if there exists constants c>0 and n0 such that for all n>n0,

In other words, g(n) bounds f(n) from above )for large n’s( up to a constant.

Examples:

(())() ngOnf ()() ngcnf

why?()()(5

()(4

()39010000(3

()50000000005.0(2(1)1000000(1

2

2

5000000

nOn

nOn

nOn

nOnO

בתודה למתרגל אלמוני באוניברסיטה העברית על השקופית

Page 22: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

32 23() nnnT nnnT 35()

()() 3nOnT

n2 25n23n

1000

3000

2000

משמעות סדרי גודל:

n100

דוגמא

שימו לבבתודה למרצה באוניברסיטת תל אביב על השקופית

Page 23: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

השוואת סדרי גודל

ספרות24מספר השניות מאז המפץ הגדול -- מספר בן ספרות80מספר הפרוטונים ביקום – מספר בן

בתודה לד"ר מירב חדד וראובן קאשי

10 100 1000

1 1 1 1

log10 n 1 2 3

n 10 100 1000

n2 100 10000 106

2n 1024 ספרות302מספר בן ספרות31מספר בן

n! 36x106 מספר גדול באמת ספרות161מספר בן

Page 24: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

?למה משתמשים במדדים אסימפטוטיים כיון שהם לא משתנים גם אם המחשבים נעשים

מהירים יותר, או שפת התכנות משתפרתמסתירים את הקבועים המאפיינים מחשב מסוייםמבליטים את אופן התנהגות האלגוריתם בקלט גדול

?זה גם חיסרון עבורנו כמהנדסים – למה

Page 25: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big – Omega חסם תחתון:

Definition: if there exists constants c>0 and n0 such that for all n>n0,

In other words, g(n) bounds f(n) from below )for large n’s( up to a constant.

Examples:

(())() ngnf ()() ngcnf

()(4()(3

()10000(2()5.0(1

2

2

nnnn

nnnn

בתודה למתרגל אלמוני באוניברסיטה העברית על השקופית

Page 26: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big – Theta: חסם עליון ותחתון Definition: if:

and

In other words, g(n) is a tight estimate of f(n) )in asymptotic terms(.

Examples:

(())() ngnf

()(3()(2

()5.0(1

2

2

nnnn

nn

(())() ngnf

(())() ngOnf

בתודה למתרגל אלמוני באוניברסיטה העברית על השקופית

Page 27: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

(())() ngOnf

cg(n)

f(n)

n0

(())() ngnf

f(n)

cg(n)

n0

(())() ngnf

f(n)c2g(n)

c1g(n)

n0

ציור מדדי סיבוכיות

בתודה למרצה באוניברסיטת תל אביב על השקופית

Page 28: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

חיפוש איבר במערך1. For i1 to n2. If A[i] = k 3. return i4. return Nil

Best Case: Tbest)n( = C = O)1( Worst Case: Tworst)n( = C+n*B+D = O)n( Average Case: Taverage)n( <= C)n+C(/2 = O)n(

Page 29: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Complexity and Performance

Some algorithms are better than others for solving the same problem

We can’t just measure run-time, because the number will vary depending on

what language was used to implement the algorithm, how well the program was written

how fast the computer ishow good the compiler ishow fast the hard disk was…

Page 30: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Basic idea: counting operations Each algorithm performs a sequence of basic

operations: Arithmetic: )low + high(/2 Comparison: if ) x > 0 ( … Assignment: temp = x Looping: while ) true ( { … } …

Idea: count the number of basic operations performed on the input

Page 31: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

It DependsDifficulties:

Which operations are basic?Not all operations take the same

amount of timeOperations take different times with

different hardware or compilers

Page 32: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Sample running times of basic Java operations (ran them in a loop…)

Loop Overhead ; 196 10

Double division d = 1.0 / d; 400 77

Method call o.m)(; 372 93

Object Construction o=new SimpleObject)(;

1080 110

Sys1: PII, 333MHz, jdk1.1.8, -nojitSys2: PIII, 500MHz, jdk1.3.1

Operation Loop Body nSec/iterationSys1 Sys2

Page 33: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

So instead…We use mathematical functions that

estimate or bound:the growth rate of a problem’s difficulty, orthe performance of an algorithm

Our Motivation: analyze the running time of an algorithm as a function of only simple parameters of the input

Page 34: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Asymptotic Running Factors Operation counts are only problematic in terms of

constant factors. The general form of the function describing the running

time is invariant over hardware, languages or compilers!

public static int myMethod(int n) { int sq = 0; for(int j=0; j < n ; j++) for(int k=0; k < n ; k++) sq++; return sq;}

• Running time is “about” n2

• We use “Big-O” notation, and say that the running time is O)n2(

Page 35: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

The Problem’s SizeThe problem’s size is stated in terms of

n, which might be:the number of components in an arraythe number of items in a filethe number of pixels on a screenthe amount of output the program is

expected to produce

Page 36: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example

Linear growth in complexity )searching an array, one component after another, to find an element(:

n

number of components

time toperformthesearch

Page 37: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Another example

Polynomial growth: the quadratic growth of the problem of visiting each pixel on the screen, where n is the length of a side of the screen:

n

length of the side of the screen

time tovisitallpixels

n2

polynomial

Page 38: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Does this matter?Yes!!! Even though computers get faster at an

alarming rate, the time complexity of an algorithm still has a great affect on what can be solved

Consider 5 algorithms, with time complexity log2 N N N log2 N N2

2N

Page 39: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Asymptotic Behavior of (Some) Functions

Page 40: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Some NumbersConsider 5 algorithms, with time

complexity n n log2 n n2

n3

2n

Page 41: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Limits on problem size asdetermined by growth rate

Algorithm Time Maximum problem sizeComplexity 1 sec 1 min 1 hour

A1 n 1000 6 x 104 3.6 x 106

A2 n log2 n 140 48932.0 x 105

A3 n2 31 244 1897A4 n3 10 39 153A5 2n 9 15 21

Assuming one unit of time equals one millisecond.

Page 42: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Effect of tenfold speed-up

Algorithm Time Maximum problem sizeComplexity before speed-up after speed-up

A1 n s1 10s1

A2 n log2 n s2 Approx. 10s2

(for large s2)A3 n2 s3 3.16s3

A4 n3 s4 2.15s4

A5 2n s5 s5 + 3.3

Page 43: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Functions as Approximations

form namemeaning for very big n

Task (n) = (f(n)) ‘omega’ f(n) is underestimate or lower bound

Task (n) = ~(f(n)) ‘tilde’ f(n) is almost exactly correct

Task (n) = O(f(n)) ‘big O’ f(n) is an overestimate or upper bound

Task (n) = o(f(n)) ‘little o’ f(n) increasingly overestimates

Page 44: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big O NotationBig O notation is the most useful for us;

it says that a function f)n( serves as an upper bound on real-life performance.

For algorithm A of size n )informally(:The complexity of A)n( is on the order of f)n( if A)n( is less than or equal to some constant times f)n(

The constant can be anything as long as the relation holds once n reaches some threshold.

Page 45: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big O Notation

A(n) is O(f(n)) as n increases without limit if there are constants C and

k such thatA(n) C*f(n) for every n >

kThis is useful because is focuses on growth rates. An algorithm with complexity n, one with complexity 10n, and one with complexity 13n + 73, all have the same growth rate. As n doubles, cost doubles.(We ignore the “73”, because we can increase 13 to 14, i.e., 14n 13n + 73 for all n 73.)

Page 46: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Big O Notation This is a mathematically formal way of ignoring constant factors, and

looking only at the “shape” of the function A=O)f( should be considered as saying that “A is at most f, up to

constant factors” We usually will

have A be therunning time ofan algorithm andf a nicely writtenfunction. E.g. Therunning time ofthe algorithm onthe right is O)n2(

public static int myMethod(int n) { int sq = 0; for(int j=0; j < n ; j++) for(int k=0; k < n ; k++) sq++; return sq;}

Page 47: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation Constant factors may be ignored

k > 0kf isO( f)

Page 48: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation Constant factors may be ignored

k > 0kf isO( f) Higher powers grow faster

nr isO( ns) if 0 r s

Page 49: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation Constant factors may be ignored

k > 0kf isO( f) Higher powers grow faster

nr isO( ns) if 0 r s Fastest growing term dominates a sum

If f is O(g), then f + g is O(g) eg an4 + bn3 is O(n4 )

Page 50: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation Constant factors may be ignored

k > 0kf isO( f) Higher powers grow faster

nr isO( ns) if 0 r s Fastest growing term dominates a sum

If f is O(g), then f + g is O(g) eg an4 + bn3 is O(n4 )

Polynomial’s growth rate is determined by leading term If f is a polynomial of degree d,

then f is O(nd)

Page 51: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation f is O(g) is transitive

If f is O(g) and g is O(h) then f is O(h)

Page 52: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation f is O(g) is transitive

If f is O(g) and g is O(h) then f is O(h) Product of upper bounds is upper bound for the

product If f is O(g) and h is O(r) then fh is O(gr)

Page 53: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation f is O(g) is transitive

If f is O(g) and g is O(h) then f is O(h) Product of upper bounds is upper bound for the

product If f is O(g) and h is O(r) then fh is O(gr)

Exponential functions grow faster than powersnk isO( bn ) b > 1 and k 0

eg n20 is O( 1.05n)

Page 54: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation f is O(g) is transitive

If f is O(g) and g is O(h) then f is O(h) Product of upper bounds is upper bound for the product

If f is O(g) and h is O(r) then fh is O(gr) Exponential functions grow faster than powers

nk isO( bn ) b > 1 and k 0eg n20 is O( 1.05n)

Logarithms grow more slowly than powerslogbn isO( nk) b > 1 and k 0

eg log2n is O( n0.5)

Page 55: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation f is O(g) is transitive

If f is O(g) and g is O(h) then f is O(h) Product of upper bounds is upper bound for the product

If f is O(g) and h is O(r) then fh is O(gr) Exponential functions grow faster than powers

nk isO( bn ) b > 1 and k 0eg n20 is O( 1.05n)

Logarithms grow more slowly than powerslogbn isO( nk) b > 1 and k 0

eg log2n is O( n0.5)

Important!

Page 56: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation All logarithms grow at the same rate

logbn is O(logdn) b, d > 1

Page 57: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Properties of the O notation All logarithms grow at the same rate

logbn is O(logdn) b, d > 1

Sum of first n rth powers grows as the (r+1)th power kr is( nr+1 )

eg i = is ( n2 )

k=1

n

k=1

n n(n+1)2

Page 58: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Polynomial and Intractable Algorithms Polynomial Time complexity

An algorithm is said to be polynomial if it is O( nd ) for some integer d

Polynomial algorithms are said to be efficientThey solve problems in reasonable times!

Intractable algorithms Algorithms for which there is no known polynomial time

algorithm We will come back to this important class later in the course

Page 59: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Analysing an Algorithm

Simple statement sequence s1; s2; …. ; sk

O(1) as long as k is constant Simple loops

for(i=0;i<n;i++) { s; } where s is O(1) Time complexity is n O(1) or O(n)

Nested loops for(i=0;i<n;i++) for(j=0;j<n;j++) { s; }

Complexity is n O(n) or O(n2)

This part isO(n)

Page 60: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Analysing an Algorithm Loop index doesn’t vary linearly

h = 1;while ( h <= n ) { s; h = 2 * h;

}h takes values 1, 2, 4, … until it exceeds n There are 1 + log2n iterations Complexity O(log n)

Page 61: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Analysing an Algorithm Loop index depends on outer loop index

for(j=0;j<n;j++) for(k=0;k<j;k++){ s; }

Inner loop executed 1, 2, 3, …., n times

Complexity O(n2) n

i =i=1

n(n+1)2

Distinguish this case -where the iteration count increases (decreases) by a constant O(nk)from the previous one -where it changes by a factor O(log n)

Page 62: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Asymptotic Analysis of Algorithms

We usually embark on an asymptotic worst case analysis of the running time of the algorithm.

Asymptotic: Formal, exact, depends only on the algorithm Ignores constantsApplicable mostly for large input sizes

Worst Case:Bounds on running time must hold for all inputsThus the analysis considers the worst-case inputSometimes the “average” performance can be much betterReal-life inputs rarely “average” in any formal sense

Page 63: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Worst Case/Best Case

Worst case performance measure of an algorithm states an upper bound

Best case complexity measure of a problem states a lower bound; no algorithm can take less time

Page 64: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Multiplicative Factors Because of multiplicative factors, it’s not always

clear that an algorithm with a slower growth rate is better

If the real time complexities were A1 = 1000n, A2 = 100nlog2n, A3 = 10n2, A4 = n3, andA5 = 2n, then A5 is best for problems with n between 2 and 9, A3 is best for problems with n between 10 and 58, A2 is best for n between 59 and 1024, and A1 is best for bigger n.

Page 65: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

An Example: Binary SearchBinary search splits the unknown

portion of the array in half; the worst-case search will be O)log2n)

Doubling n only increases the logarithm by 1; growth is very slow

Page 66: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example: Insertion Sort(reminder)

18 2235 97 8455611047starting order:

182235 978455611047

move through the array, keeping the left side ordered;when we find the 35, we have to slide the 18 over to make room:

182235 978455611047

continue moving through the array, always keeping the leftside ordered, and sliding values over as necessary to do so:

18 slid over

18 slid over

Page 67: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example: Insertion Sort

• Sum from 1 to N would be: )N*)N+1((/2

• So sum from 1 to N-1 is))N-1(*N(/2

• Worst case for insertion sort is thus N2/2 – N/2

• In other words, O)N2(

Page 68: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Asymptotic Behavior of (Some) Functions

N grows much slower than N2, so we ignore the N term

Page 69: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Selection Sort and Bubble Sort Similar analyses tell us that both Selection Sort and

Bubble Sort have time complexity of O)N2(

Selection Sort

182235 97 84 55 61 1047182235 97 84 55 61 104718223597 84 55 61 104718224797 84 61 55 103518224797 84 61 55 103518224797 84 61 55 103518224797 84 61 55 103518224797 84 61 55 103518224797 84 61 55 1035

Bubble Sort

18 223597 84 5561 10 4718 223597 84 5561 10 4718 22 3597 84 5561 1047

18223597 84 5561 104718223597 84 5561 1047

18223597 84 5561 1047

18 2235 97 84 55 61 10 4718223597 84 55 61 10 471822 3597 84 55 61 10 47

Page 70: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Some Complexity ExamplesFor each of the following examples:1. What task does the function perform?2. What is the time complexity of the function?3. Write a function which performs the same

task but which is an order-of-magnitude )not a constant factor( improvement in time complexity

Page 71: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 1public int someMethod1 (int[] a) {

int temp = 0;for (int i=0; i < a.length; i++)

for (int j=i+1; j < a.length; j++)if (Math.abs(a[j]-a[i]) > temp) temp = Math.abs(a[j]-a[i]);

return temp;}

Page 72: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 1

1. Finds maximum difference between two values in the array

public int someMethod1 (int[] a) {int temp = 0;for (int i=0; i < a.length; i++)

for (int j=i+1; j < a.length; j++)if (Math.abs(a[j]-a[i]) > temp) temp = Math.abs(a[j]-a[i]);

return temp;}

Page 73: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 1

1. Finds maximum difference between two values in the array2. O)n2(

public int someMethod1 (int[] a) {int temp = 0;for (int i=0; i < a.length; i++)

for (int j=i+1; j < a.length; j++)if (Math.abs(a[j]-a[i]) > temp) temp = Math.abs(a[j]-a[i]);

return temp;}

Page 74: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 1public int someMethod1 (int[] a) {

int temp = 0;for (int i=0; i < a.length; i++)

for (int j=i+1; j < a.length; j++)if (Math.abs(a[j]-a[i]) > temp) temp = Math.abs(a[j]-a[i]);

return temp;}1. Finds maximum difference between two values in the array2. O)n2(3. Find the max and min values in the array, then subtract one

from the other – the problem will be solved in O)n(

Page 75: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 2: a[ ] is sorted in increasing order, b[ ] is not sorted

public boolean someMethod2(int[] a, int[] b) {for (int j=0; j < b.length; j++)

for (int i=0; i < a.length-1; i++)if (b[j] == a[i] + a[i+1])

return true;return false;

}

Page 76: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 2: a[ ] is sorted in increasing order, b[ ] is not sorted

1. Checks whether a value in b[ ] equals the sum of two consecutive values in a[ ]

public boolean someMethod2(int[] a, int[] b) {for (int j=0; j < b.length; j++)

for (int i=0; i < a.length-1; i++)if (b[j] == a[i] + a[i+1])

return true;return false;

}

Page 77: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 2: a[ ] is sorted in increasing order, b[ ] is not sorted

1. Checks whether a value in b[ ] equals the sum of two consecutive values in a[ ]

2. O)n2(

public boolean someMethod2(int[] a, int[] b) {for (int j=0; j < b.length; j++)

for (int i=0; i < a.length-1; i++)if (b[j] == a[i] + a[i+1])

return true;return false;

}

Page 78: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 2: a[ ] is sorted in increasing order, b[ ] is not sorted

1. Checks whether a value in b[ ] equals the sum of two consecutive values in a[ ]

2. O)n2(3. For each value in b[ ], carry out a variation of a binary

search in a[ ] – the problem will be solved in O)n log n(

public boolean someMethod2(int[] a, int[] b) {for (int j=0; j < b.length; j++)

for (int i=0; i < a.length-1; i++)if (b[j] == a[i] + a[i+1])

return true;return false;

}

Page 79: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 3: each element of a[ ] is a uniqueint between 1 and n; a.length is n-1

public int someMethod3 (int[] a) {boolean flag;for (int j=1; j<=a.length+1; j++) {

flag = false;for (int i=0; i<a.length; i++) {

if (a[i]==j) {flag = true;break;

}}if (!flag) return j;

}return -1;

}

Page 80: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 3: each element of a[ ] is a uniqueint between 1 and n; a.length is n-1public int someMethod3 (int[] a) {

boolean flag;for (int j=1; j<=a.length+1; j++) {

flag = false;for (int i=0; i<a.length; i++) {

if (a[i]==j) {flag = true;break;

}}if (!flag) return j;

}return -1;

}

1. Returns the missing value )the integer between 1 and n missing in a[ ](

Page 81: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Example 3: each element of a[ ] is a uniqueint between 1 and n; a.length is n-1public int someMethod3 (int[] a) {

boolean flag;for (int j=1; j<=a.length+1; j++) {

flag = false;for (int i=0; i<a.length; i++) {

if (a[i]==j) {flag = true;break;

}}if (!flag) return j;

}return -1;

}

1. Returns the missing value )the integer between 1 and n missing in a[ ](

2. O)n2(

Page 82: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

A better solution to Example 3

public int betterMethod3 (int[] a) {int result = 0, sum, n;n = a.length+1;sum = (n*(n+1))/2;for (int i=0; i < a.length; i++)

result += a[i];return (sum-result);

}

Page 83: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

A better solution to Example 3

Time complexity O(n)

public int betterMethod3 (int[] a) {int result = 0, sum, n;n = a.length+1;sum = (n*(n+1))/2;for (int i=0; i < a.length; i++)

result += a[i];return (sum-result);

}

Page 84: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Theoretical Computer ScienceStudies the complexity of problems:

increasing the theoretical lower bound on the complexity of a problem

determining the worst-case and average-case complexity of a problem )along with best-case(

showing that a problem falls into a given complexity class )e.g., requires at least, or no more than, polynomial time(

Page 85: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Easy and Hard problems

“Easy” problems, by convention, are those that can be solved in polynomial time or less

“Hard” problems have only non-polynomial solutions: exponential or worse

Showing that a problem is easy is easy )come up with an “easy” algorithm(; proving a problem is hard is hard

Page 86: Introduction to Complexity. בעיה פשוטה במיוחד סדר שלושה מספרים לפי סדר מונוטוני עולה יש למישהו רעיון?

Theory and algorithmsTheoretical computer scientists also

devise algorithms that take advantage of different kinds of computer hardware, like parallel processors

devise probabilistic algorithms that have very good average-case performance )though worst-case performance might be very bad(

narrow the gap between the inherent complexity of a problem and the best currently known algorithm for solving it