Cover Image for Big O Notation in C
74 views

Big O Notation in C

Big O notation is a way to describe the upper bound or worst-case performance of an algorithm in terms of its input size. It’s a mathematical notation used to analyze the efficiency of algorithms and how their runtime or resource usage scales as the input size grows. Big O notation is not specific to the C programming language; it’s a concept used in computer science and algorithm analysis across various programming languages.

The notation is represented as “O(f(n)),” where “f(n)” describes the growth rate of the algorithm in terms of the input size “n.” Here are some common examples:

  1. O(1): Constant time complexity. The algorithm’s runtime doesn’t depend on the input size. For example, accessing an element of an array by index is O(1).
  2. O(log n): Logarithmic time complexity. Common in algorithms that divide the problem into smaller subproblems, such as binary search.
  3. O(n): Linear time complexity. The runtime increases linearly with the input size. For example, iterating through an array.
  4. O(n log n): Log-linear time complexity. Common in sorting algorithms like merge sort and quicksort.
  5. O(n^2): Quadratic time complexity. The runtime is proportional to the square of the input size. Common in nested loops.
  6. O(2^n): Exponential time complexity. The runtime grows exponentially with the input size. Common in recursive algorithms with multiple recursive calls.
  7. O(n!): Factorial time complexity. The worst-case runtime grows very rapidly with the input size. Common in brute-force algorithms.

In C, you analyze the time complexity of algorithms by examining how they perform operations as a function of the input size. You can measure the actual runtime using profiling tools or measure the number of basic operations executed, depending on the algorithm.

Here’s a simple example in C that demonstrates linear time complexity (O(n)) when searching for a specific element in an array:

C
#include <stdio.h>

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i; // Element found
        }
    }
    return -1; // Element not found
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int target = 3;
    int n = sizeof(arr) / sizeof(arr[0]);

    int result = linearSearch(arr, n, target);

    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

In this example, the linearSearch function has a time complexity of O(n) because it iterates through the array linearly to search for the target element.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS