You are on page 1of 2

Homework 1: CS 425 (Theory of Algorithms)

Due Date: Wednesday, Sept 4, 2018

1. We can determine how many digits a positive integer has by


repeatedly dividing by 10 (without keeping the remainder) until the
number is less than 10, consisting of only 1 digit. We add 1 to this
value for each time we divided by 10.

a) Describe the algorithm in a recursive way.


b) Implement this recursive algorithm in C++ and test it using a
main function that calls this with the values of 15, 105 and
15105. (Hint: Remember if n is an integer, n/10 will be an integer
without the fractional part.)

2. Illustrate Merge Sort Algorithm using the following data set:


24, 11, 78, 18, 10, -2, 53, 0
Show the steps, count number of comparisons, and determine the
runtime without using the formula. Compare the value with that given
by the formula.

3. Given the following function, determine the value of the function at


specific point as given.

int Sum(int N)
{
if (N == 1)
return 1;
else
return N + Sum(N/3) ;
}
Find Sum(10)
Show the steps.

What would be the runtime of the algorithm? Assume the cost of each
addition and each division is same and equal to 1. What would be the
recurrence relation for finding T(N)

4. The pseudocode for Bubble Sort is given. Write a C++ program to


implement that.
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure

You can still use the same main and other part of the program of
Selection sort (done in the lab) and call BubbleSort once you write it
properly in C++.

You might also like