1 - Intro To Algorithms
1 - Intro To Algorithms
What is an algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem, that is, for obtaining a required output for any legitimate input in a finite amount of time. Each step of an algorithm should be non-ambiguous Range of inputs for which an algorithm works should be specified Same algorithm can be represented in several different ways Several algorithms for solving the same problem could exist Algorithms for the same problem can be based on very different ideas and can solve the problem with dramatically different speeds
A simple example: finding the greatest common divisor of two nonnegative integers m and n
Problem definition: find the number that divides both m and n. Denote this number as gcd(m,n). We will discuss three different algorithms to illustrate the discussion on algorithms on the previous page. Algorithm 1. Will be based on Euclids Algorithm. Repeatedly apply the following until m mod n gives 0: gcd(m,n) = gcd (n, m mod n) where m mod n is the remainder of the division of m by n. For instance, gcd(80, 30) can be computed as gcd(80,30)=gcd(30,20)=gcd(20,10)=gcd(10,0)=10
Algorithm 3. Compute the product of the common factors of m and n as the greatest common divisor. Step 1. Find the prime factors of m Step 2. Find the prime factors of n Step 3. Identify all the common factors in the two primes expansions found in steps 1 and 2. Step 4. Compute the product of all the common factors and return it as the greatest common divisor. Note that this algorithm, as in the form given above, is not really legitimate. The reason is the fact that steps to find the primes are defined ambiguously: they require a list of prime numbers and it is not explained how to get such a list. Also, note that this algorithm is much more complex and slower than Euclids Algorithm.
Sorting Rearranging the items of a given list in ascending or descending order. For instance, sorting the list of students by their last name or by their school id number. Sorting makes many questions about lists of items easier; for instance, searching for a specific item in a given list. There are plenty of sorting algorithms. Some of them achieve efficiencies of n log(n) comparisons for sorting n elements.