4. Types of problem modification
INSTANCE
SIMPLIFICATION
Problem instance is
transformed to be
more simple to solve
Presorting
5. Types of problem modification
Representation
Change
Data structure is
transformed so that
it is more efficient to
solve.
Horner’s Rule
6. Types of problem modification
Problem
Reduction
Problem is
transformed to
different problem
whose algorithm is
already available
Finding LCM
7. Presorting to find Mode
Algorithm PresortMode(A[0...n-1])
// assumes that A is sorted
i ← 0
modefrequency ← 0
while i < n do
runlength ← 1
runvalue ← A[i]
while i+runlength < n and A[i+runlength] = runvalue do
runlength++
if runlength > modefequency then
modefrequency ← runlength
modevalue ← runvalue
i += runlength
return modevalue
8. Algorithm PresortMode(A[0...n-1])
// assumes that A is sorted
i ← 0
modefrequency ← 0
while i < n do
runlength ← 1
runvalue ← A[i]
while i+runlength < n and A[i+runlength] = runvalue do
runlength++
if runlength > modefequency then
modefrequency ← runlength
modevalue ← runvalue
i += runlength
return modevalue
10. Decrease & CONQUER
Problem of size
N
Conquering
Stage
Solve for N-1
• Problem of Size N
• Solve for N-1
• Repeat above and problem will be
reduced eventually to what we can
easily solve
11. Decrement types
• Decrease by constant
e.g. insertion sort
• Decrease by constant factor
e.g. the fake coin problem
• Decrease by variable
e.g. Euclid’s Algorithm
12. Insertion Sort
Algorithm InsertionSort(A[0...n-1])
for i ← to n-1 do // move the unsorted portion
v ← A[i] // value to sort
j ← i-1 // end of the sorted array
while j ≥ 0 and A[j] > v do // scan the sorted part of the array for
the insertion point
A[j+1] ← A[j] // shift the sort array to make room for the insertion
j--
A[j+1] ← v // insert
13. Algorithm InsertionSort(A[0...n-1])
for i ← to n-1 do
v ← A[i]
j ← i-1
while j ≥ 0 and A[j] > v do
A[j+1] ← A[j]
j--
A[j+1] ← v
Complexity:
>>O(n^2) in worst case
>>O(n) for presorted array
15. More about backtracking
• Just like Brute Force
• It is used when a problem has many candidates as solution.
• Used very commonly by hacker
• Used in electrical engineering
• Artificial intelligence
• Solving puzzles & paths
• Accuracy is guaranteed
16. Sum of Subsets
Algorithm SumOfSubset(s,k,y){
X[k] = 1;
If(s+w[k] = m)
Write (x[1:n]);
Else if((s+w[k] + w[k+1]) <= m)
SumOfSubset(s+w[k], k+1, y-w[k]);
If ((s+ y-w[k]>=m) &&(s =w[k+1] <=m)) {
X[k] =0;
SumOfSubset(s,k+1,y-w[k]);
}
}