Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

In this exercise we deal with the problem of string matching.

a) Explain how to use a brute-force algorithm to find the first occurrence of the given string m of characters, called the target, in a string nof characters, where mn, called the text. [Hint: Think in terms of finding a match for the first character of the target and checking successive characters for a match, and if they do not all match, moving the start location one character to the right.]

b) Express your algorithm in pseudo code.

c) Give a big-O estimate for the worst-case time complexity of the brute-force algorithm you described.

Short Answer

Expert verified

a) The algorithms best-case performance is when the number of comparisons made is the least, which is n - 1 in this algorithm.

b) The number of comparisons made is only one.

c) The numbers of comparisons made are log2ntimes

Subpart a)

The first term of the array is selected as max.

With the help of the loop every element is checked.

Any element that has a greater value than the selected one is taken as max.

In one iterated for loop only one comparison is made.

The loop is iterated for i = 1 to n.

Therefore the number of iterations and comparisons are n - 1.

Subpart b)

The algorithm is,

Input: x integer, (a1,a2,a3,....,an):list of distinct integers

Output: Index such thatx=ai or 0

If is not in the list.

Algorithm:

If i:=1;

Whilein andxai

Do i:=i+1;

Ifin then result:=i;;

Else result:=0;;

Return result;

Therefore the best-case scenario is when the element to be located is the first element so only one comparison is made.

Step by step solution

Achieve better grades quicker with Premium

  • Unlimited AI interaction
  • Study offline
  • Say goodbye to ads
  • Export flashcards

Over 22 million students worldwide already upgrade their learning with Vaia!

01

Subpart c)Step 1:

The algorithm will be,

ifi:=1;

f:=n;

While i < j do

m:=(i+j)2

If x>aithen i: = m + 1 else j: = m;

If x=aithen result: = i; else result: = 0;

Return result;

02

Step 2:

We divide the set in to half|log2n|number of times.

Therefore the numbers of comparisons made are|log2n| times

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Study anywhere. Anytime. Across all devices.

Sign-up for free