## Homework Assignment 4

### Brute Force and Divide-and-Conquer Algorithms

#### Due: Thursday, March 13, at 12:30 PM

1. Consider the common brute-force string matching algorithm below. How many comparisons, successful and unsuccessful, will this algorithm make in searching a text consisting of 1000 zeroes for each of these patterns?
• 0100
• 00001

2. Use the partitioning idea seen in binary search to design an algorithm that finds a subrange of an sorted array.
• input
• a sorted array, A[0..n-1]
• two integers, lower and upper
• output: the subrange of the array that contains all values v such that lowervupper. That is:
• a pair [indexL, indexU] such that
• 0 ≤ indexL ≤ indexU ≤ n-1 and
• lower ≤ A[indexL] ≤ A[indexU] ≤ upper
If no such range exists, return -1.

3. Develop a divide-and-conquer algorithm that computes the position of the largest element in an unsorted array of n elements. What is the output of your algorithm when several elements in the array are the same largest value?

4. Consider the the divide-and-conquer multiplication algorithm we learned in Session 14.

• Demonstrate the algorithm by computing 1710 * 1011.
• Why does this algorithm not outperform conventional multiplication algorithms until the numbers become quite long?

#### Deliverables

By the due date and time, submit a hardcopy of your solutions. You may bring your solutions to class (preferred) and leave them on the desk before class begins, or you may leave them in my mailbox in the department office.

#### A Brute-Force String Matching Algorithm

```    // Input : Array S[0..n-1] of n characters (the string)
//         Array P[0..m-1] of m characters (the pattern)
// Output: the index of the first character in the string
//         that starts a substring that matches the pattern,
//         or -1 if the search fails

for i ← 0 to n-m do
j ← 0
while j < m and P[j] == S[i+j] do
j ← j + 1
if j == m
return i

return -1
```

Eugene Wallingford ..... wallingf@cs.uni.edu ..... March 11, 2014