Professional Documents
Culture Documents
Lars Kulik
Lecture 5
Semester 1, 2022
1
Brute Force Algorithms
• Selection sort
• String matching
• Closest pair
• Exhaustive search for combinatorial solutions
• Graph traversal
2
Example: Selection Sort
A sorting algorithm is
4
Properties of Selection Sort
In-place?
Stable?
Input-insensitive? ✎
5
Brute Force String Matching
for i ← 0 to n − m do
j ←0
while j < m and p[j] = t[i + j] do
j ←j +1
if j = m then
return i
return −1
6
Analysing Brute Force String Matching
8
The Closest Pair Problem (Two-Dimensional Case)
y •
•
• •
• • •
•
•
• •
• •
•
x
9
The Closest Pair Problem (Two-Dimensional Case)
y •
•
• •
• • •
•
•
• •
• •
•
x
9
Brute Force Geometric Algorithms: Closest Pair
min ← ∞
for i ← 0 to n − 2 do
for j ← i + 1 to n − 1 do
d ← sqrt((xi − xj )2 + (yi − yj )2 )
if d < min then
min ← d
p1 ← i
p2 ← j
return p1 , p2
10
Analysing the Closest Pair Algorithm
How?
11
Brute Force Summary
12
Exhaustive Search
Problem type:
Find the shortest tour (visiting each node exactly once before
returning to the start) in a weighted undirected graph.
2 a−b−c −d −a : 18
a b
a−b−d −c −a : 11
a−c −b−d −a : 23
5 3 a−c −d −b−a : 11
7
8 a−d −b−c −a : 23
c d a−d −c −b−a : 18
1
14
Example 2: Knapsack
• weights: w1 , w2 , . . . , wn
• values: v1 , v2 , . . . , vn
• knapsack of capacity W
find the most valuable selection of items that will fit in the
knapsack.
15
Example 2: Knapsack
W = 10 w1 = 7 w2 = 3 w3 = 4 w4 = 5
v1 = 42 v2 = 12 v3 = 40 v4 = 25
18
Hamiltonian Tours
2 6
4 5
19
Eulerian Tours
1 3
2 6
4 5
20
Hard and Easy Problems
Graphs.
22