Sobes.tech
Junior — Middle

Can you give an example of estimating the time complexity of one of the sorting algorithms?

sobes.tech AI

Answer from AI

Let's consider an example of estimating the time complexity of the Bubble Sort algorithm.

The algorithm passes through the list multiple times, comparing neighboring elements and swapping them if they are in the wrong order.

  • In the worst and average case, the algorithm performs approximately n*(n-1)/2 comparisons, where n is the number of elements.
  • Therefore, the time complexity is O(n²).

Example code in Python:

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]

This algorithm is inefficient for large arrays due to its quadratic complexity.