Anda di halaman 1dari 4

Notion of Algorithm

CSC 3102

1.1

B.B. Karki, LSU

Program: Algorithms + Data Structures

Program
Solving the problem

Algorithm
Problems solution

Data Structure
Problems instance

N. Wirth, Algorithms + Data Structures = Programs Prentice-Hall, Englewood Cliffs, NJ 1976


CSC 3102
1.2

B.B. Karki, LSU

What is an Algorithm?
n An algorithm is a sequence of unambiguous instructions for solving a problem
F Obtaining a required output for any

legitimate input in a finite amount of time F Procedural solutions to problems. n Computer is capable of understanding

problem

and following the instructions given.


n An input specifies an instance of the

algorithm

problem the algorithm solves. input computer output

CSC 3102

1.3

B.B. Karki, LSU

Motivation for Algorithm

n Theoretical importance
F The study of algorithms represents the core of computer

science.

n Practical importance
F A practitioners toolkit of known algorithms F Framework for designing and analyzing algorithms for new

problems.

CSC 3102

1.4

B.B. Karki, LSU

GCD Algorithms

n Problem: Finding the greatest common divisor of two nonnegative, not-

both-zero integers, m and n, denoted gcd(m,n).


n Algorithms: Several algorithms exist for solving this problem F Euclids algorithm: Apply repeatedly the equality gcd(m,n)=gcd(n,m mod n) until m mod n is 0. The last value of m is the gcd. F Definition-based algorithm: Start by checking whether t = min{m,n} divides both m and n: If it does, t is the answer; if not, decrease t by 1 and try again. The last value of t which divides both integers is the gcd. F Middle-school algorithm: Find the prime factors of both m and n, identify all the common factors whose product is the gcd.

CSC 3102

1.5

B.B. Karki, LSU

Sequential Search: Pseudocode

Algorithm SequentialSearch(A[0..n-1],K) //Searches for a given value in a given array by sequential search //Input: An array A[0..n-1] and a search key K //Output: Returns the index of the first element of A that matches K // or -1 if there are no matching elements i0 while i < n and A[i] K do i i +1 if i < n return i else return -1

CSC 3102

1.6

B.B. Karki, LSU

Binary Search: Pseudocode

Algorithm BinarySearch(A[0..n-1],K) //Implements a nonrecursive binary search //Input: An array A[0..n-1] sorted in ascending order and a search key K //Output: An index of the arrays element that is equal to K // or -1 if there is no such element l 0; r n-1 while l r do m (l +r)/2 if K = A[m] return m elseif K < A[m] r < m-1 else l m+1 return -1

CSC 3102

1.7

B.B. Karki, LSU

Characteristics of Algorithm
n Finiteness: F terminates after a finite number of steps n Definiteness: F rigorously and unambiguously specified n Input: F valid inputs are clearly specified n Output: F can be proved to produce the correct output given a valid input n Effectiveness: F steps are sufficiently simple and basic.
CSC 3102
1.8

B.B. Karki, LSU