Chapter 2
Chapter 2
Numerical Problems
1 Perform analysis on bubble sort
Time Complexity: O ( n2 )
Space Complexity: O ( 1 )
Bubble Sort is generally not used in practice because it is very inefficient for large
datasets.
2 Perform analysis on the summation of an array
Time Complexity: O ( n )
Space Complexity: O ( 1 )
The performance of this algorithm is generally very good, especially for small to
medium-sized arrays.
3 Perform analysis of finding the maximum of an array
Time Complexity: O ( n )
Space Complexity: O ( 1 )
The performance of this algorithm is generally very good, especially for small to
medium-sized arrays.
4 Let t(n) = 7 n3 +6 n2+5 , prove that this is O(n3 )
t(n) = 7 n3 +6 n2+5 ≤ 7 n3 +6 n 3+5 n3=18 n3 ≈ O ( n3 )
Programming Exercise
1 Write an algorithm for swapping two variables without an intermediate variable.
1. a = a + b
2. b = a - b
3. a = a - b
At step 2 and step 3, one could notice that the values in a and b are swapped without
intermediate variable.
2 Write an algorithm for finding a number prime or not.
Input: n, number
Output: True (If n is prime number) or False (If n is not prime number)
if n < 2:
return False
if n = 2 or 3:
3 Read a set of employees and their year of birth. Write an algorithm to print the
employees who were born in odd years.
1. Read in the set of employees and their year of birth.
2. For each employee, check if their birth year is odd.
3. If the birth year is odd, print the employee's name and birth year.
4 Write an algorithm to check the number Armstrong number or not.
sum = 0
num_digits = len(str(n))
for digit in str(n):
sum += int(digit) ** num_digits
if sum == n:
return True
else:
return False
5 Write an algorithm to solve the towers of Hanoi problem.
1. If there is only one disk, move it from the source rod to the destination rod.
2. Otherwise, move n-1 disks from the source rod to the auxiliary rod, using the
destination rod as the auxiliary.
3. Move the remaining disk from the source rod to the destination rod.
4. Move the n-1 disks from the auxiliary rod to the destination rod, using the source
rod as the auxiliary.
6 Write a recursive algorithm to find the sum of an array.
def array_sum(arr, index):
if index < 0:
return 0
return arr[index] + array_sum(arr, index - 1)
7 Write an algorithm for solving a binary search problem.
def binary_search(arr, value, first, last):
if first > last:
return -1
for i in range(len(denominations)):
num_coins = total_amount // denominations[i]
coin_counts[i] = num_coins
total_amount -= denominations[i] * num_coins
if total_amount == 0:
return coin_counts