i for j

Chapter 3
Brute force
Exhaustive search
Exponentiation
Problem: Given a and n, compute an.
Solution: multiply 1 by a n times
Efficiency:
Algorithm: Selection Sort
Input: An array A[0..n − 1] of orderable elements
Output: The same array sorted in ascending order
for i ← 0 to n − 2 do
min ← i
for j ← i + 1 to n − 1 do
if A[j] < A[min] then min ← j
swap A[i] and A[min]
A0
A1
...
in their final positions
A
i-1
A i , . . ., A min ,. . ., An-1
the last n-i elements
Example of selection sort
String Matching
Pattern:
Text:
a string of m characters to search for
a (long) string of n characters to search in
Algorithm:
1. Align pattern at beginning of text
2. moving from left to right, compare each character of
pattern to the corresponding character in text until
• all characters are found to match (successful search); or
• a mismatch is detected
3. while pattern is not found and the text is not yet exhausted,
realign pattern one position to the right and repeat step 2.
String matching examples
1. Pattern: 001011
Text: 10010101101001100101111010
2. Pattern: happy
Text: It is never too late to have a happy
childhood
Efficiency:
Closest Pair problem
Problem: find two closest points among n
points in k-dimensional space
Algorithm: Compute the distance between
each pair of points (let’s look at two dims.)
Efficiency:
Convex Hull problem
Problem: find the smallest convex polygon
enclosing n points in the plane
Algorithm: For each pair of points p1 and
p2, determine whether all other points lie to
the same side of the line through p1 and p2.
Efficiency: