Docsity

Introduction - Algorithm - Study Notes, Study notes of Algorithms and Programming

Partial preview of the text

Download Introduction - Algorithm - Study Notes and more Study notes Algorithms and Programming in PDF only on Docsity!

Design and Analysis of Algorithms

Chapter 1

Introduction

1.1 Origin of word: Algorithm

The word Algorithm comes from the name of the muslim author Abu Ja’far Mohammad ibn Musa al-Khowarizmi. He was born in the eighth century at Khwarizm (Kheva), a town south of river Oxus in present Uzbekistan. Uzbekistan, a Muslim country for over a thousand years, was taken over by the Russians in 1873.

His year of birth is not known exactly. Al-Khwarizmi parents migrated to a place south of Baghdad when he was a child. It has been established from his contributions that he flourished under Khalifah Al-Mamun at Baghdad during 813 to 833 C.E. Al-Khwarizmi died around 840 C.E.

Much of al-Khwarizmi’s work was written in a book titled al Kitab al-mukhatasar fi hisab al-jabr wa’l-muqabalah (The Compendious Book on Calculation by Completion and Balancing). It is from the titles of these writings and his name that the words algebra and algorithm are derived. As a result of his work, al-Khwarizmi is regarded as the most outstanding mathematician of his time

1.2 Algorithm: Informal Definition

An algorithm is any well-defined computational procedure that takes some values, or set of values, as input and produces some value, or set of values, as output. An algorithm is thus a sequence of computational steps that transform the input into output.

1.3 Algorithms, Programming

A good understanding of algorithms is essential for a good understanding of the most basic element of computer science: programming. Unlike a program, an algorithm is a mathematical entity, which is independent of a specific programming language, machine, or compiler. Thus, in some sense, algorithm

1.5. COURSE IN REVIEW 9

open eye to implementation issues down the line that will be important for final implementation. For example, we will study three fast sorting algorithms this semester, heap-sort, merge-sort, and quick-sort. From our mathematical analysis, all have equal running times. However, among the three (barring any extra considerations) quick sort is the fastest on virtually all modern machines. Why? It is the best from the perspective of locality of reference. However, the difference is typically small (perhaps 10-20% difference in running time).

Thus this course is not the last word in good program design, and in fact it is perhaps more accurately just the first word in good program design. The overall strategy that I would suggest to any programming would be to first come up with a few good designs from a mathematical and algorithmic perspective. Next prune this selection by consideration of practical matters (like locality of reference). Finally prototype (that is, do test implementations) a few of the best designs and run them on data sets that will arise in your application for the final fine-tuning. Also, be sure to use whatever development tools that you have, such as profilers (programs which pin-point the sections of the code that are responsible for most of the running time).

1.5 Course in Review

This course will consist of four major sections. The first is on the mathematical tools necessary for the analysis of algorithms. This will focus on asymptotics, summations, recurrences. The second element will deal with one particularly important algorithmic problem: sorting a list of numbers. We will show a number of different strategies for sorting, and use this problem as a case-study in different techniques for designing and analyzing algorithms.

The final third of the course will deal with a collection of various algorithmic problems and solution techniques. Finally we will close this last third with a very brief introduction to the theory of NP-completeness. NP-complete problem are those for which no efficient algorithms are known, but no one knows for sure whether efficient solutions might exist.

1.6 Analyzing Algorithms

In order to design good algorithms, we must first agree the criteria for measuring algorithms. The emphasis in this course will be on the design of efficient algorithm, and hence we will measure algorithms in terms of the amount of computational resources that the algorithm requires. These resources include mostly running time and memory. Depending on the application, there may be other elements that are taken into account, such as the number disk accesses in a database program or the communication bandwidth in a networking application.

In practice there are many issues that need to be considered in the design algorithms. These include issues such as the ease of debugging and maintaining the final software through its life-cycle. Also, one of the luxuries we will have in this course is to be able to assume that we are given a clean, fully-specified mathematical description of the computational problem. In practice, this is often not the case, and the algorithm must be designed subject to only partial knowledge of the final specifications. Thus, in practice

10 CHAPTER 1. INTRODUCTION

it is often necessary to design algorithms that are simple, and easily modified if problem parameters and specifications are slightly modified. Fortunately, most of the algorithms that we will discuss in this class are quite simple, and are easy to modify subject to small problem variations.

1.7 Model of Computation

Another goal that we will have in this course is that our analysis be as independent as possible of the variations in machine, operating system, compiler, or programming language. Unlike programs, algorithms to be understood primarily by people (i.e. programmers) and not machines. Thus gives us quite a bit of flexibility in how we present our algorithms, and many low-level details may be omitted (since it will be the job of the programmer who implements the algorithm to fill them in).

But, in order to say anything meaningful about our algorithms, it will be important for us to settle on a mathematical model of computation. Ideally this model should be a reasonable abstraction of a standard generic single-processor machine. We call this model a random access machine or RAM.

A RAM is an idealized machine with an infinitely large random-access memory. Instructions are executed one-by-one (there is no parallelism). Each instruction involves performing some basic operation on two values in the machines memory (which might be characters or integers; let’s avoid floating point for now). Basic operations include things like assigning a value to a variable, computing any basic arithmetic operation (+, - , × , integer division) on integer values of any size, performing any comparison (e.g. x ≤ 5 ) or boolean operations, accessing an element of an array (e.g. A[ 10 ]). We assume that each basic operation takes the same constant time to execute.

This model seems to go a good job of describing the computational power of most modern (nonparallel) machines. It does not model some elements, such as efficiency due to locality of reference, as described in the previous lecture. There are some “loop-holes” (or hidden ways of subverting the rules) to beware of. For example, the model would allow you to add two numbers that contain a billion digits in constant time. Thus, it is theoretically possible to derive nonsensical results in the form of efficient RAM programs that cannot be implemented efficiently on any machine. Nonetheless, the RAM model seems to be fairly sound, and has done a good job of modelling typical machine technology since the early 60’s.

1.8 Example: 2-dimension maxima

Let us do an example that illustrates how we analyze algorithms. Suppose you want to buy a car. You want the pick the fastest car. But fast cars are expensive; you want the cheapest. You cannot decide which is more important: speed or price. Definitely do not want a car if there is another that is both faster and cheaper. We say that the fast, cheap car dominates the slow, expensive car relative to your selection criteria. So, given a collection of cars, we want to list those cars that are not dominated by any other.

Here is how we might model this as a formal problem.

  • Let a point p in 2-dimensional space be given by its integer coordinates, p = (p.x, p.y).
12 CHAPTER 1. INTRODUCTION

This English description is clear enough that any (competent) programmer should be able to implement it. However, if you want to be a bit more formal, it could be written in pseudocode as follows:

MAXIMA(int n, Point P[1... n]) 1 for i ← 1 to n 2 do maximal ← true 3 for j ← 1 to n 4 do 5 if (i 6 = j) and (P[i].x ≤ P[j].x) and (P[i].y ≤ P[j].y) 6 then maximal ← false; break 7 if (maximal = true) 8 then output P[i]

There are no formal rules to the syntax of this pseudo code. In particular, do not assume that more detail is better. For example, I omitted type specifications for the procedure Maxima and the variable maximal, and I never defined what a Point data type is, since I felt that these are pretty clear from context or just unimportant details. Of course, the appropriate level of detail is a judgement call. Remember, algorithms are to be read by people, and so the level of detail depends on your intended audience. When writing pseudo code, you should omit details that detract from the main ideas of the algorithm, and just go with the essentials.

You might also notice that I did not insert any checking for consistency. For example, I assumed that the points in P are all distinct. If there is a duplicate point then the algorithm may fail to output even a single point. (Can you see why?) Again, these are important considerations for implementation, but we will often omit error checking because we want to see the algorithm in its simplest form.

Here are a series of figures that illustrate point domination.

(2,5) (4,4)

(5,1)

(4,11)

(7,7)

(7,13)

(11,5)

(12,12) (9,10) (14,10)

(15,7)

(13,3)

Figure 1.2: Points that dominate (4, 11)

(2,5) (4,4)

(5,1)

(4,11)

(7,7)

(7,13)

(11,5)

(12,12) (9,10) (14,10)

(15,7)

(13,3)

Figure 1.3: Points that dominate (9, 10)

1.10. RUNNING TIME ANALYSIS 13

(2,5) (4,4)

(5,1)

(4,11)

(7,7)

(7,13)

(11,5)

(12,12) (9,10) (14,10)

(15,7)

(13,3)

Figure 1.4: Points that dominate (7, 7)

(2,5) (4,4)

(5,1)

(4,11)

(7,7)

(7,13)

(11,5)

(12,12) (9,10) (14,10)

(15,7)

(13,3)

Figure 1.5: The maximal points

1.10 Running Time Analysis

The main purpose of our mathematical analysis will be measuring the execution time. We will also be concerned about the space (memory) required by the algorithm.

The running time of an implementation of the algorithm would depend upon the speed of the computer, programming language, optimization by the compiler etc. Although important, we will ignore these technological issues in our analysis.

To measure the running time of the brute-force 2-d maxima algorithm, we could count the number of steps of the pseudo code that are executed or, count the number of times an element of P is accessed or, the number of comparisons that are performed.

The running time depends upon the input size, e.g. n Different inputs of the same size may result in different running time. For example, breaking out of the inner loop in the brute-force algorithm depends not only on the input size of P but also the structure of the input.

Two criteria for measuring running time are worst-case time and average-case time.

Worst-case time is the maximum running time over all (legal) inputs of size n. Let I denote an input instance, let |I| denote its length, and let T (I) denote the running time of the algorithm on input I. Then Tworst(n) = max |I|=n

T (I)

Average-case time is the average running time over all inputs of size n. Let p(I) denote the probability of seeing this input. The average-case time is the weighted sum of running times with weights

1.10. RUNNING TIME ANALYSIS 15

The analysis involved computing a summation. Summation should be familiar but let us review a bit here. Given a finite sequence of values a 1 , a 2 ,... , an, their sum a 1 + a 2 +... + an is expressed in summation notation as (^) n ∑

i= 1

ai

If n = 0 , then the sum is additive identity, 0.

Some facts about summation: If c is a constant

∑^ n

i= 1

cai = c

∑^ n

i= 1

ai

and (^) n ∑

i= 1

(ai + bi) =

∑^ n

i= 1

ai +

∑^ n

i= 1

bi

Some important summations that should be committed to memory.

Arithmetic series ∑n

i= 1

i = 1 + 2 +... + n

n(n + 1 ) 2

= Θ(n^2 )

Quadratic series

∑^ n

i= 1

i^2 = 1 + 4 + 9 +... + n^2

2n^3 + 3n^2 + n 6

= Θ(n^3 )

Geometric series ∑n

i= 1

xi^ = 1 + x + x^2 +... + xn

x(n+^1 )^ − 1 x − 1

= Θ(n^2 )

If 0 < x < 1 then this is Θ( 1 ), and if x > 1, then this is Θ(xn).

Harmonic series For n ≥ 0

Hn =

∑^ n

i= 1

i

= 1 +

n

≈ ln n

= Θ(ln n)

16 CHAPTER 1. INTRODUCTION

1.11 Analysis: A Harder Example

Let us consider a harder example.

NESTED-LOOPS()

1 for i ← 1 to n 2 do 3 for j ← 1 to 2i 4 do k = j... 5 while (k ≥ 0 ) 6 do k = k − 1...

How do we analyze the running time of an algorithm that has complex nested loop? The answer is we write out the loops as summations and then solve the summations. To convert loops into summations, we work from inside-out.

Consider the inner most while loop.

NESTED-LOOPS()

1 for i ← 1 to n 2 do for j ← 1 to 2i 3 do k = j 4 while (k ≥ 0 ) J 5 do k = k − 1

It is executed for k = j, j − 1, j − 2,... , 0. Time spent inside the while loop is constant. Let I() be the time spent in the while loop. Thus

I(j) =

∑^ j

k= 0

1 = j + 1

Consider the middle for loop.

NESTED-LOOPS()

1 for i ← 1 to n 2 do for j ← 1 to 2i J 3 do k = j 4 while (k ≥ 0 ) 5 do k = k − 1

18 CHAPTER 1. INTRODUCTION

points, P = {p 1 , p 2 ,... , pn} in 2-space a point is said to be maximal if it is not dominated by any other point in P. The problem is to output all the maximal points of P. We introduced a brute-force algorithm that ran in Θ(n^2 ) time. It operated by comparing all pairs of points. Is there an approach that is significantly better?

The problem with the brute-force algorithm is that it uses no intelligence in pruning out decisions. For example, once we know that a point pi is dominated by another point pj, we do not need to use pi for eliminating other points. This follows from the fact that dominance relation is transitive. If pj dominates pi and pi dominates ph then pj also dominates ph; pi is not needed.

1.11.2 Plane-sweep Algorithm

The question is whether we can make an significant improvement in the running time? Here is an idea for how we might do it. We will sweep a vertical line across the plane from left to right. As we sweep this line, we will build a structure holding the maximal points lying to the left of the sweep line. When the sweep line reaches the rightmost point of P , then we will have constructed the complete set of maxima. This approach of solving geometric problems by sweeping a line across the plane is called plane sweep.

Although we would like to think of this as a continuous process, we need some way to perform the plane sweep in discrete steps. To do this, we will begin by sorting the points in increasing order of their x-coordinates. For simplicity, let us assume that no two points have the same y-coordinate. (This limiting assumption is actually easy to overcome, but it is good to work with the simpler version, and save the messy details for the actual implementation.) Then we will advance the sweep-line from point to point in n discrete steps. As we encounter each new point, we will update the current list of maximal points.

We will sweep a vertical line across the 2-d plane from left to right. As we sweep, we will build a structure holding the maximal points lying to the left of the sweep line. When the sweep line reaches the rightmost point of P, we will have the complete set of maximal points. We will store the existing maximal points in a list The points that pi dominates will appear at the end of the list because points are sorted by x-coordinate. We will scan the list left to right. Every maximal point with y-coordinate less than pi will be eliminated from computation. We will add maximal points onto the end of a list and delete from the end of the list. We can thus use a stack to store the maximal points. The point at the top of the stack will have the highest x-coordinate.

Here are a series of figures that illustrate the plane sweep. The figure also show the content of the stack.

1.11. ANALYSIS: A HARDER EXAMPLE 19

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

sweep line

stack

(2,5)

Figure 1.6: Sweep line at (2, 5)

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

stack

sweep line

(3,13)

Figure 1.7: Sweep line at (3, 13)

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

stack

sweep line

(3,13)

(4,11)

Figure 1.8: Sweep line at (4, 11)

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

stack

sweep line

(3,13)

(4,11)

(5,1)

Figure 1.9: Sweep line at (5, 1)

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

stack

sweep line

(3,13)

(4,11)

(7,7)

Figure 1.10: Sweep line at (7, 7)

2 4 6 8 10 12 14 16 18

2

4

6

8

10

14 12

(2,5)

(5,1)

(4,11)

(7,7)

(3,13)

(10,5)

(12,12) (9,10) (14,10) (15,7)

(13,3)

stack

sweep line

(3,13)

(4,11)

(9,10)

Figure 1.11: Sweep line at (9, 10)

1.11. ANALYSIS: A HARDER EXAMPLE 21

1.11.3 Analysis of Plane-sweep Algorithm

Sorting takes Θ(n log n); we will show this later when we discuss sorting. The for loop executes n times. The inner loop (seemingly) could be iterated (n − 1 ) times. It seems we still have an n(n − 1 ) or Θ(n^2 ) algorithm. Got fooled by simple minded loop-counting. The while loop will not execute more n times over the entire course of the algorithm. Why is this? Observe that the total number of elements that can be pushed on the stack is n since we execute exactly one push each time during the outer for-loop.

We pop an element off the stack each time we go through the inner while-loop. It is impossible to pop more elements than are ever pushed on the stack. Therefore, the inner while-loop cannot execute more than n times over the entire course of the algorithm. ( Make sure that you understand this ).

The for-loop iterates n times and the inner while-loop also iterates n time for a total of Θ(n). Combined with the sorting, the runtime of entire plane-sweep algorithm is Θ(n log n).

1.11.4 Comparison of Brute-force and Plane sweep algorithms

How much of an improvement is plane-sweep over brute-force? Consider the ratio of running times:

n^2 nlogn

n log n

n logn (^) lognn 100 7 15 1000 10 100 10000 13 752 100000 17 6021 1000000 20 50171

For n = 1, 000, 000, if plane-sweep takes 1 second, the brute-force will take about 14 hours!. From this we get an idea about the importance of asymptotic analysis. It tells us which algorithm is better for large values of n. As we mentioned before, if n is not very large, then almost any algorithm will be fast. But efficient algorithm design is most important for large inputs, and the general rule of computing is that input sizes continue to grow until people can no longer tolerate the running times. Thus, by designing algorithms efficiently, you make it possible for the user to run large inputs in a reasonable amount of time.