Sobes.tech
Junior — Middle

Describe an example of an algorithm and evaluate its time complexity.

sobes.tech AI

Answer from AI

Let's consider an example of a bubble sort algorithm for an array of numbers:

Idea: iterate through the array, compare neighboring elements, and swap them if they are in the wrong order. Repeat passes until the array is sorted.

Example in Dart (Flutter):

void bubbleSort(List<int> arr) {
  int n = arr.length;
  for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
}

The time complexity of this algorithm is O(n²), where n is the number of elements in the array. This is because, in the worst case, the algorithm makes approximately n passes through the array, and on each pass compares elements almost n times.

This algorithm is simple but inefficient for large data. More efficient sorting algorithms, such as quicksort or merge sort, are used for better performance.

Describe an example of an algorithm and evaluate its… - sobes.tech