0% found this document useful (0 votes)
7 views

CS 201 Lecture 13 - Algorithms

Uploaded by

aljubehjihad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

CS 201 Lecture 13 - Algorithms

Uploaded by

aljubehjihad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Dr.

Kholoud Nairoukh
Department of Computer Science
German-Jordanian University
Lecture 13
• The foundation of computer programming.

• Most generally; a definite procedure for


performing some sort of task.

• A computer program is simply a description of an


algorithm, in a language precise enough for a
computer to understand, requiring only operations
that the computer already knows how to do.

• We say that a program implements (or “is an


implementation of”) its algorithm.

Dr. Kholoud Nairoukh


• Grade-school arithmetic algorithms:
– How to add any two natural numbers
written in decimal on paper, using carries.
– Similar: Subtraction using borrowing.
– Multiplication & long division.

• How to register for classes at GJU.

Dr. Kholoud Nairoukh


• Some common programming languages:
– Newer: Java, C, C++, C#, Visual Basic,
JavaScript, Perl, Pascal, many others…
– Older: Fortran, Cobol, Lisp, Basic
– Assembly languages, for low-level coding.

• In this class we will use an informal,


Pascal-like “pseudo-code” language.
• You should know at least 1 real language!

Dr. Kholoud Nairoukh


• Task: Given a sequence {ai}=a1,…,an, aiN, say what
its largest element is.

• One algorithm for doing this, in English:


– Set the value of a temporary variable v (largest
element seen so far) to a1’s value.
– Look at the next element ai in the sequence.
– If ai>v, then re-assign v to the number ai.
– Repeat then previous 2 steps until there are no
more elements in the sequence, & return v.

Dr. Kholoud Nairoukh


• When you start up a piece of software, we
say the program, or its algorithm are being
run or executed by the computer.

• Given a description of an algorithm, you can


also execute it by hand, by working through
all of its steps with pencil & paper.

• Before ~1940, “computer” meant a person


whose job was to execute algorithms!

Dr. Kholoud Nairoukh


• Let {ai}=7,12,3,15,8. Find its maximum…
• Set v = a1 = 7.
• Look at next element: a2 = 12.
• Is a2>v? Yes, so change v to 12.
• Look at next element: a2 = 3.
• Is 3>12? No, leave v alone….
• Is 15>12? Yes, v=15…

Dr. Kholoud Nairoukh


Some important general features of algorithms:

• Input. Information or data that comes in.


• Output. Information or data that goes out.
• Definiteness. Algorithm is precisely defined.
• Correctness. Outputs correctly relate to inputs.
• Finiteness. Won’t take forever to describe or run.
• Effectiveness. Individual steps are all do-able.
• Generality. Works for many possible inputs.
• Efficiency. Takes little time & memory to run.

Dr. Kholoud Nairoukh


Dr. Kholoud Nairoukh
Procedure

• procedure procname(arg: type)


Declares that the following text defines a
procedure named procname that takes inputs
(arguments) named arg which are data objects
of the type.

Example:
procedure maximum(L: list of integers)
[statements defining maximum…]
Dr. Kholoud Nairoukh
• An assignment statement evaluates the
expression expression, then reassigns the
expression value to the variable variable.

– Example assignment statement:


v := 3x+7 (If x is 2, changes v to 13.)

• In pseudocode (but not real code), the


expression might be informally stated:
x := the largest integer in the list L

Dr. Kholoud Nairoukh


• Sometimes we may write a statement as an
informal English imperative, if the meaning is
still clear and precise.

• Example: “swap x and y”

• Keep in mind that real programming


languages never allow this.

• Break down algorithm into detailed steps.


Dr. Kholoud Nairoukh
Dr. Kholoud Nairoukh
• Not executed .

• Natural-language text explaining some aspect of


the procedure to human readers.

• Also called a remark in some real programming


languages, e.g. BASIC.

• Example: It might appear in a max algorithm:


{Note that v is the largest integer seen so far.}

Dr. Kholoud Nairoukh


• Evaluate the propositional (Boolean)
expression condition.
– If the resulting truth value is True, then
execute the statement statement;
– otherwise, just skip on ahead to the next
statement after the if statement.

• Variant: if cond then stmt1 else stmt2


– Like before, but iff truth value is False,
executes stmt2.

Dr. Kholoud Nairoukh


• Evaluate the propositional (Boolean)
expression condition.

• If the resulting value is True, then execute


statement.

• Continue repeating the above two actions


over and over until finally the condition
evaluates to False; then proceed to the next
statement.
Dr. Kholoud Nairoukh
• Its equivalent to infinite nested ifs:

if condition
begin
statement
if condition
begin
statement
…(continue infinite nested if’s)
end
end

Dr. Kholoud Nairoukh


• Initial is an integer expression.

• Final is another integer expression.

• Semantics: Repeatedly execute stmt, first with


variable var := initial, then with var := initial+1,
then with var := initial+2, etc., then finally with
var := final.

• Question: What happens if stmt changes the


value of var, or the value that initial or final
evaluates to?

Dr. Kholoud Nairoukh


• For can be exactly defined in terms of while:
begin
var := initial
while var  final
begin
stmt
var := var + 1
end
end

Dr. Kholoud Nairoukh


• procedure(argument)
A procedure call statement invokes the named
procedure, giving it the argument expression as
its input.

• Various real programming languages refer to


procedures as functions (since the procedure
call notation works similarly to function
application f(x)), or as subroutines,
subprograms, or methods.

Dr. Kholoud Nairoukh


Write a pseudocode procedure to find the
maximum number in a list of integers.
procedure max(a1, a2, …, an: integers)
v := a1 {largest element so far}
for i := 2 to n {go through rest of elements}
if ai > v then v := ai {found bigger}
{at this point v’s value is the same as
the largest integer in the list}
return v
Dr. Kholoud Nairoukh
• Suppose we ask you to write an algorithm to
compute the predicate:
IsPrime:N→{T,F}
– Computes whether a given natural number
is a prime number.

• First, start with a correct predicate-logic


definition of the desired function:
n: IsPrime(n)  ¬1<d<n: d|n
Means d divides n
evenly (without remainder)

Dr. Kholoud Nairoukh


• It can be rewritten as a universal: Means d does not
divide n evenly
(the remainder is
¬1<d<n: d|n  1<d<n: d | n ≠0)
 2≤ d ≤ n−1: d | n
• This universal can then be translated directly into a
corresponding for loop:
for d := 2 to n−1 { Try all potential divisors >1 & <n }
if d|n then return F { n has divisor d; not prime }
return T { no divisors were found; n must be prime}

Dr. Kholoud Nairoukh


• Problem of searching an ordered list.
– Given a list L of n elements that are
sorted into a definite order (e.g., numeric,
alphabetical),
– And given a particular element x,
– Determine whether x appears in the list,
– and if so, return its index (position) in the
list.
• Problem occurs often in many contexts.
• Let’s find an efficient algorithm!
Dr. Kholoud Nairoukh
procedure linear search

(x: integer, a0, a1, …, an: distinct integers)


i := 0 {start at beginning of list}
while (i  n  x  ai) {not done, not found}
i := i + 1 {go to the next position}
if i  n then location := i+1 {it was found}
else location := -1 {it wasn’t found}
return location {index or -1 if not found}

Dr. Kholoud Nairoukh


Dr. Kholoud Nairoukh
procedure binary search

procedure binary search


(x:integer, a1, a2, …, an: distinct integers)
i := 1 {left endpoint of search interval}
j := n {right endpoint of search interval}
while i<j begin {while interval has >1 item}
m := (i+j)/2 {midpoint}
if x>am then i := m+1 else j := m
end
if x = ai then location := i else location := 0
return location
Dr. Kholoud Nairoukh
Write an algorithm that finds the sum of all
integers in a list consists of at least 2 minimum
elements.

Solution:
procedure sum(a1, a2, …, an: integers)
s := 0 {sum of elements so far}
for i := 1 to n {go through all elements}
s := s + ai {add current item}
{at this point s is the sum of all items}
return s
Dr. Kholoud Nairoukh
• Sorting is a common operation in many
applications.
– Example: spreadsheets and databases.

• It is also widely used as a subroutine in other


data-processing algorithms.

• Two well known sorting algorithms:


– Bubble sort However, these are not
very efficient, and you should
– Insertion sort not use them on large data sets!

Dr. Kholoud Nairoukh


Dr. Kholoud Nairoukh
• English description of algorithm:

For each item in the input list,


“Insert” it into the correct place in the sorted
output list generated so far.
– Use linear or binary search to find the
location where the new item should be
inserted.
– Then, shift the items from that position
onwards down by one position.
– Put the new item in the hole remaining.

Dr. Kholoud Nairoukh


• Characteristics of algorithms.
• Pseudocode.
• Examples: Max algorithm, primality-testing,
linear search & binary search algorithms.
Sorting.
• Intuitively we see that binary search is much
faster than linear search, but how do we analyze
the efficiency of algorithms formally?
• Use methods of algorithmic complexity, which
utilize the order-of-growth concepts.

Dr. Kholoud Nairoukh

You might also like