0% found this document useful (0 votes)
11 views32 pages

BİM122 Lecture Note 6

Uploaded by

halilahmetkural
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views32 pages

BİM122 Lecture Note 6

Uploaded by

halilahmetkural
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter 3

With Question/Answer Animations

Copyright © McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education.
Chapter Summary
 Algorithms
 Example Algorithms
 Algorithmic Paradigms
 Growth of Functions
 Big-O and other Notation
 Complexity of Algorithms
Section 3.1
Section Summary
 Properties of Algorithms
 Algorithms for Searching and Sorting
Problems and Algorithms
 In many domains there are key general problems that
ask for output with specific properties when given
valid input.
 The first step is to precisely state the problem, using
the appropriate structures to specify the input and the
desired output.
 We then solve the general problem by specifying the
steps of a procedure that takes a valid input and
produces the desired output. This procedure is called
an algorithm.
Algorithms Abu Ja’far Mohammed Ibin Musa Al-Khowarizmi
( )
Definition: An algorithm is a finite set of precise
instructions for performing a computation or for solving a
problem.
Example: Describe an algorithm for finding the maximum
value in a finite sequence of integers.
Solution: Perform the following steps:
1. Set the temporary maximum equal to the first integer in the
sequence.
2. Compare the next integer in the sequence to the temporary
maximum.
 If it is larger than the temporary maximum, set the temporary
maximum equal to this integer.
3. Repeat the previous step if there are more integers. If not, stop.
4. When the algorithm terminates, the temporary maximum is the
largest integer in the sequence.
Specifying Algorithms
 Algorithms can be specified in different ways. Their steps can be
described in English or in pseudocode.
 Pseudocode is an intermediate step between an English language
description of the steps and a coding of these steps using a
programming language.
 The form of pseudocode we use is specified in Appendix . It uses
some of the structures found in popular languages such as C++ and
Java.
 Programmers can use the description of an algorithm in pseudocode to
construct a program in a particular language.
 Pseudocode helps us analyze the time required to solve a problem
using an algorithm, independent of the actual programming language
used to implement algorithm.
Properties of Algorithms
 Input: An algorithm has input values from a specified set.
 Output: From the input values, the algorithm produces the
output values from a specified set. The output values are
the solution.
 Correctness: An algorithm should produce the correct
output values for each set of input values.
 Finiteness: An algorithm should produce the output after a
finite number of steps for any input.
 Effectiveness: It must be possible to perform each step of
the algorithm correctly and in a finite amount of time.
 Generality: The algorithm should work for all problems of
the desired form.
Finding the Maximum Element in a
Finite Sequence
 The algorithm in pseudocode:

procedure max(a1, a2, …., an: integers)


max := a1
for i := to n
if max < ai then max := ai
return max{max is the largest element}

 Does this algorithm have all the properties listed on


the previous slide?
Some Example Algorithm Problems
 Two classes of problems will be studied in this
section.
1. Searching Problems: finding the position of a
particular element in a list.
2. Sorting problems: putting the elements of a list into
increasing order.
3. Optimization Problems: determining the optimal
value (maximum or minimum) of a particular
quantity over all possible inputs
Searching Problems
Definition: The general searching problem is to locate
an element x in the list of distinct elements a1,a2,...,an,
or determine that it is not in the list.
 The solution to a searching problem is the location of
the term in the list that equals x (that is, i is the
solution if x = ai) or if x is not in the list.
 For example, a library might want to check to see if a
patron is on a list of those with overdue books before
allowing him/her to checkout another book.
 We will study two different searching algorithms; linear
search and binary search.
Linear Search Algorithm
 The linear search algorithm locates an item in a list by examining elements in
the sequence one at a time, starting at the beginning.
 First compare x with a1. If they are equal, return the position .
 If not, try a2. If x = a2, return the position .
 Keep going, and if no match is found when the entire list is scanned,
return .
procedure linear search(x:integer,
a1, a2, …,an: distinct integers)
i :=
while (i n and x ≠ ai)
i := i +
if i n then location := i
else location :=
return location{location is the subscript of the term that
equals x, or is if x is not found}
Binary Search
 Assume the input is a list of items in increasing order.
 The algorithm begins by comparing the element to be found
with the middle element.
 If the middle element is lower, the search proceeds with the upper
half of the list.
 If it is not lower, the search proceeds with the lower half of the list
(through the middle position).
 Repeat this process until we have a list of size .
 If the element we are looking for is equal to the element in the list,
the position is returned.
 Otherwise, is returned to indicate that the element was not
found.
 In Section , we show that the binary search algorithm is
much more efficient than linear search.
Binary Search
 Here is a description of the binary search algorithm in
pseudocode.
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Binary Search
Example: The steps taken by a binary search for in the list:

1. th

2. th
th

3. th
th th

4. th
th
th

5.
Binary Search Video
 https://www.youtube.com/watch?v=iP897Z5Nerk
 https://www.youtube.com/watch?v=j5uXyPJ0Pew
Sorting
 To sort the elements of a list is to put them in increasing order
(numerical order, alphabetic, and so on).
 Sorting is an important problem because:
 A nontrivial percentage of all computing resources are devoted to
sorting different kinds of lists, especially applications involving large
databases of information that need to be presented in a particular
order (e.g., by customer, part number etc.).
 An amazing number of fundamentally different algorithms have been
invented for sorting. Their relative advantages and disadvantages have
been studied extensively.
 Sorting algorithms are useful to illustrate the basic notions of
computer science.
 A variety of sorting algorithms are studied in this book; binary,
insertion, bubble, selection, merge, quick, and tournament.
 In Section , we’ll study the amount of time required to sort a list
using the sorting algorithms covered in this section.
Bubble Sort
 Bubble sort makes multiple passes through a list.
Every pair of elements that are found to be out of
order are interchanged.

procedure bubblesort(a1,…,an: real numbers


with n ≥ )
for i := to n
for j := to n i
if aj >aj+1 then interchange aj and aj+1
{a1,…, an is now in increasing order}
Bubble Sort
Example: Show the steps of bubble sort with


 nd


Bubble Sort Video
 https://www.youtube.com/watch?v=lyZQPjUT5
B4
 https://www.youtube.com/watch?v=Jdtq5uKz-
w4
Insertion Sort
 Insertion sort begins with the nd element. It compares the nd element
with the st and puts it before the first if it is not larger.
procedure insertion sort
•Next the 3rd element is put into (a1,…,an:
the correct position among the real numbers with n ≥ )
first 3 elements. for j := to n
•In each subsequent pass, the n+ st
i :=
element is put into its correct while aj > ai
position among the first n+
i := i +
elements.
•Linear search is used to find the
m := aj
correct position. for k := to j i
aj-k := aj-k-1
ai := m
{Now a1,…,an is in increasing order}
Insertion Sort
Example: Show all the steps of insertion sort with the
input:
first two positions are interchanged)
element remains in its position)
fourth is placed at beginning)
element remains in its position)
Insertion Sort Video
 https://www.youtube.com/watch?v=ROalU379l3U
 https://www.youtube.com/watch?v=i-SKeOcBwko
Greedy Algorithms
 Optimization problems minimize or maximize some parameter over all possible
inputs.
 Among the many optimization problems we will study are:
 Finding a route between two cities with the smallest total mileage.
 Determining how to encode messages using the fewest possible bits.
 Finding the fiber links between network nodes using the least amount of fiber.
 Optimization problems can often be solved using a greedy algorithm, which
makes the “best” choice at each step. Making the “best choice” at each step does
not necessarily produce an optimal solution to the overall problem, but in
many instances, it does.
 After specifying what the “best choice” at each step is, we try to prove that this
approach always produces an optimal solution, or find a counterexample to
show that it does not.
 The greedy approach to solving problems is an example of an algorithmic
paradigm, which is a general approach for designing an algorithm. We return to
algorithmic paradigms in Section
Greedy Algorithms: Making Change
Example: Design a greedy algorithm for making change
(in U.S. money) of n cents with the following coins:
quarters ( cents), dimes ( cents), nickels ( cents), and
pennies ( cent) , using the least total number of coins.
Idea: At each step choose the coin with the largest possible
value that does not exceed the amount of change left.
1. If n = cents, first choose quarter leaving
Greedy Change-Making Algorithm
Solution: Greedy change-making algorithm for n cents. The
algorithm works with any coin denominations c1, c2, …,cr .
procedure change(c1, c2, …, cr: values of coins, where c1> c2> … > cr ;
n: a positive integer)
for i :=
di := di counts the coins of denomination ci]
while n ci
di := di + ci
n n - ci
di counts the coins ci]

 For the example of U.S. currency, we may have quarters, dimes,


nickels and pennies, with c1 = c2 = c3 = c4 =
Greedy Change-Making Algorithm
 Optimality depends on the denominations available.
 For U.S. coins, optimality still holds if we add half
dollar coins ( cents) and dollar coins ( cents).
 But if we allow only quarters ( cents), dimes (
cents), and pennies ( cent), the algorithm no longer
produces the minimum number of coins.
 Consider the example of cents. The optimal number
of coins is , i.e., dimes and penny. What does the
algorithm output?
Greedy Scheduling
Example: We have a group of proposed talks with start and end times.
Construct a greedy algorithm to schedule as many as possible in a
lecture hall, under the following assumptions:
 When a talk starts, it continues till the end.
 No two talks can occur at the same time.
 A talk can begin at the same time that another ends.
 Once we have selected some of the talks, we cannot add a talk which
is incompatible with those already selected because it overlaps at least
one of these previously selected talks.
 How should we make the “best choice” at each step of the algorithm?
That is, which talk do we pick ?
 The talk that starts earliest among those compatible with already chosen talks?
 The talk that is shortest among those already compatible?
 The talk that ends earliest among those compatible with already chosen talks?
Greedy Scheduling
 Picking the shortest talk doesn’t work.
Start: 8:00 AM

Talk Start: 9:00 AM

Talk
Start: 9:45 AM

End :9:45 AM
End: 10:00 AM Talk

End: 11:00 AM

 Can you find a counterexample here?


 But picking the one that ends soonest does work. The
algorithm is specified on the next page.
Greedy Scheduling algorithm
Solution: At each step, choose the talks with the
earliest ending time among the talks compatible with
those selected.
procedure schedule(s1 s2 … sn : start times, e1 e2 … en :
end times)
sort talks by finish time and reorder so that e1 e2 … en
S :=
for j :=
if talk j is compatible with S then
S := S {talk j}

 Will be proven correct by induction in Chapter 5.


Exercises
 Algorithms
 Chapter 3.1 (7th Global Edition): 2, 3, 4, 7, 11, 13, 29, 34,
35
 Chapter 3.1. (7th Edition): 2, 3, 5, 9, 13, 15, 34, 41, 42

31
References
 Discrete Mathematics and Its Applications, Seventh Edition, Kenneth Rosen

32

You might also like