L2_New
L2_New
فصل دوم
فهرست مطالب
مقدمهای بر الگوریتمها و مفاهیم پایه
معرفی پیچیدگی زمانی و حافظهای و روشهای تحلیل مسائل
معرفی ساختمان دادههای مقدماتی و الگوریتمهای وابسته به آنها
آرایه •
صف •
پشته •
لیست پیوندی •
تئوری درخت و گراف و الگوریتمهای مرتبط
الگوریتمهای مرتبسازی و تحلیل پیچیدگی مربوط به آنها
مباحث تکمیلی در ساختمان دادهها
3
سوال
• اگر دو الگوریتم داشته باشیم که یک هدف را انجام دهند ،چگونه باید فهمید که کدام بهتر
عمل میکنند؟
Space Complexity
S(P)=C+SP(I)
• Fixed Space Requirements (C)
Independent of the characteristics of the inputs and
outputs
▫ instruction space
▫ space for simple variables, fixed-size structured variable,
constants
• Variable Space Requirements (SP(I))
depend on the instance characteristic I
▫ number, size, values of inputs and outputs associated with I
▫ recursive stack space, formal parameters, local variables, return
address
5
Example
Program 1.9: Simple arithmetic function
Sabc(I) = 0
float abc(float a, float b, float c)
{
return a + b + b * c + (a + b - c) / (a + b) + 4.00;
}
Example (Cont.)
*Program 1.11: Recursive function for summing a list of numbers (p.20)
float rsum(float list[ ], int n)
{
if (n > 0) return rsum(list, n-1) + list[n-1];
return 0;
} Srsum(I) = Srsum(n)= 6n
Time Complexity
T(P)=C+TP(I)
• Compile time (C)
independent of instance characteristics
• run (execution) time TP
• Definition
A program step is a syntactically or semantically
meaningful program segment whose execution
time is independent of the instance
characteristics.
• Example
▫ abc = a + b + b * c + (a + b - c) / (a + b) + 4.0
▫ abc = a + b + c
8
Home Work 1
19
Asymptotic Notation
• How does the algorithm behave as the problem size gets very large?
21
22
23
24
25
• Definition(Big oh)
• f(n) = O(g(n)) iff there exist positive constants c and n0 such that f(n)
cg(n) for all n, n n0.
• Examples
▫ 3n+2=O(n)/* 3n+24n for n2 */
▫ 3n+3=O(n)/* 3n+34n for n3 */
▫ 100n+6=O(n) /* 100n+6101n for n10 */
▫ 10n2+4n+2=O(n2) /* 10n2+4n+211n2 for n5 */
▫ 6*2n+n2=O(2n) /* 6*2n+n2 7*2n for n4 */
26
• O(1): constant
• O(n): linear
• O(n2): quadratic
• O(n3): cubic
• O(2n): exponential
• O(logn) logarithmic
• O(nlogn) log linear
27
Practical Complexity
250
f(n) = n
f(n) = log(n)
f(n) = n log(n)
f(n) = n^2
f(n) = n^3
f(n) = 2^n
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
28
f(n) = n
f(n) = log(n)
f(n) = n log(n)
f(n) = n^2
f(n) = n^3
f(n) = 2^n
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
29
1000
f(n) = n
f(n) = log(n)
f(n) = n log(n)
f(n) = n^2
f(n) = n^3
f(n) = 2^n
0
1 3 5 7 9 11 13 15 17 19
30
5000
4000
f(n) = n
f(n) = log(n)
3000
f(n) = n log(n)
f(n) = n^2
2000 f(n) = n^3
f(n) = 2^n
1000
0
1 3 5 7 9 11 13 15 17 19
31
Definition: f(n) = Θ(g(n)) iff there exist positive constants c1, c2, and
n0 such that c1g(n) ≤ f(n) ≤ c2g(n) for all n, n ≥ n0.
45
Home Work 2