Loading...

DESIGN & ANALYSIS OF ALGORITHMS  

LEARNING OUTCOME 3

Algorithm Complexity

Algorithm complexity refers to the computational resources (typically time and space) required by an algorithm to solve a problem. It is a measure of how efficient an algorithm is in terms of its resource usage as the input size grows.

Two Types of Algorithm Complexity

Need for Algorithm Analysis

Algorithm Complexities

Big O notation

Big O notation is a mathematical way to describe how an algorithm's performance (usually its runtime) grows as the input size increases. It focuses on the worst-case scenario and ignores constant factors and lower-order terms, giving us a simplified way to compare algorithms. Common notations include O(1) for constant time, O(log n) for logarithmic time, O(n) for linear time, O(n log n) for linearithmic time, O(n^2) for quadratic time, and O(2^n) for exponential time.

Algorithm Time and Space Complexities

Algorithm complexity is a measure of how efficient an algorithm is in terms of its resource usage (time and space). It is typically expressed using Big O notation, which provides an upper bound on the growth rate of the algorithm's running time or space usage as the input size increases.

Common Time Complexities

Common Space Complexities

Calculating Time Complexity

  1. Identify the Input Size (n):
    • Determine what represents the input size for the specific algorithm.
    • This is usually the size of the input data structure, such as the length of an array, the number of nodes in a tree, or the number of characters in a string.
  2. Identify the Basic Operations:
    • Pinpoint the fundamental operations within the algorithm, such as:
      • Arithmetic operations (+, -, *, /)
      • Comparisons (<, >, ==, !=)
      • Assignments (=)
      • Function calls
      • Loop iterations
  3. Analyze the Loop Structure:
    • Nested Loops: Multiply the number of iterations of each loop to get the total number of operations.
    • Single Loops: Count the number of iterations based on the loop condition and the increment/decrement.
  4. Determine the Dominant Term:
    • Identify the term that grows the fastest as the input size n increases.
    • This term will dominate the overall time complexity.
  5. Apply Big O Notation:
    • Ignore constant factors and lower-order terms.
    • Express the dominant term using Big O notation.

Example: Bubble Sort

Let's analyze the time complexity of the bubble sort algorithm:

void bubbleSort(int arr[], int n) {
			for (int i = 0; i < n - 1; i++) {
				for (int j = 0; j < n - i - 1; j++) {
					if (arr[j] > arr[j + 1]) {
						swap(arr[j], arr[j + 1]);
					}
				}
			}
		}
  1. Input Size: n (the number of elements in the array)
  2. Basic Operations: Comparisons and swaps.
  3. Loop Analysis:
    • Outer loop: n-1 iterations
    • Inner loop: n-i-1 iterations in the i-th outer loop iteration
  4. Dominant Term: The nested loops contribute to a time complexity of O(n^2).
  5. Big O Notation: The time complexity is O(n^2).

This means that as the input size n increases, the runtime of bubble sort grows quadratically.

Analyzing Space Complexity

Space complexity measures the amount of extra memory an algorithm uses as a function of the input size.

Steps to Analyze Space Complexity:

  1. Identify Auxiliary Space:
    • Determine the extra space used by the algorithm beyond the input data.
    • This includes variables, data structures, and function call stacks.
  2. Express in Big O Notation:
    • Represent the auxiliary space as a function of the input size.

Example: Bubble Sort

For bubble sort, the auxiliary space used is constant, regardless of the input size. This includes:

Therefore, the space complexity of bubble sort is O(1).

Other Examples:

Key Points:

EXAMPLES:

Time Complexity Questions and Answers

  1. Question: What is the time complexity of linear search?
    • Answer: O(n). In the worst case, the algorithm needs to iterate through all n elements of the array.
  2. Question: What is the time complexity of binary search?
    • Answer: O(log n). Binary search repeatedly halves the search space, leading to logarithmic time complexity.
  3. Question: What is the time complexity of merge sort?
    • Answer: O(n log n). Merge sort divides the array into two halves, recursively sorts them, and then merges them in linear time. This leads to a time complexity of O(n log n).

Space Complexity Questions and Answers

  1. Question: What is the space complexity of iterative bubble sort?
    • Answer: O(1). Iterative bubble sort only uses a constant amount of extra space for variables like i, j, and a temporary variable for swapping.
  2. Question: What is the space complexity of recursive Fibonacci?
    • Answer: O(n). Each recursive call adds to the function call stack, leading to linear space complexity.
  3. Question: What is the space complexity of merge sort?
    • Answer: O(n). Merge sort requires extra space for the temporary array used to merge the sorted halves. This extra space is proportional to the input size.

1. What is the time complexity of the following code snippet?

	void linearSearch(int arr[], int n, int x) {
		for (int i = 0; i < n; i++) {
			if (arr[i] == x) {
				return i;
			}
		}
		return -1;
	}
			

Answer

2. Analyze the time complexity of the following recursive function:

	int factorial(int n) {
		if (n == 0) {
			return 1;
		} else {
			return n * factorial(n - 1);
		}
	}
			

Answer:

The factorial function calculates the factorial of a given integer n using recursion. The base case is when n is 0, in which case the function returns 1 (since 0! = 1). Otherwise, the function returns n multiplied by the factorial of n-1, which is calculated by recursively calling the factorial function itself.

Example Usage:

	#include <iostream>
	
	int main() {
		int num = 5;
		int result = factorial(num);
		std::cout << "The factorial of " << num << " is: " << result << std::endl;  // Output: 120
		return 0;
	}
			

3. What is the time complexity of the following nested loop?

int factorial(int n) {
return (n == 0) ? 1 : n * factorial(n - 1);
}
	

Answer

4. What is the space complexity of the following function:

int factorial(int n) {
if (n == 0) {
	return 1;
} else {
	return n * factorial(n - 1);
}
}
	

Answer

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: