Visualizing the Bubble Sort algorithm in Flutter

1. What Is Bubble Sort?

Bubble Sort is one of the simplest sorting algorithms. It works by repeatedly swapping adjacent elements if they are in the wrong order. This process continues until the array is sorted.

Despite its simplicity, Bubble Sort is rarely used in practice for large datasets because of its inefficiency, but it’s a great algorithm for teaching the fundamentals of sorting and iteration.


2. How Bubble Sort Works

The core idea is to “bubble up” the largest unsorted value to its correct position by comparing adjacent pairs:

  1. Compare the first and second elements.
  2. If the first is greater than the second, swap them.
  3. Move to the next pair and repeat.
  4. After one full pass, the largest element is at the end.
  5. Repeat the process for the rest of the array, excluding the sorted portion.

3. Bubble Sort Pseudocode

for i from 0 to n - 1
    for j from 0 to n - i - 2
        if array[j] > array[j + 1]
            swap array[j] and array[j + 1]

4. Step-by-Step Example

Let’s walk through sorting the array: [5, 3, 8, 4, 2]

Pass 1:

  • Compare 5 and 3 → Swap → [3, 5, 8, 4, 2]
  • Compare 5 and 8 → OK
  • Compare 8 and 4 → Swap → [3, 5, 4, 8, 2]
  • Compare 8 and 2 → Swap → [3, 5, 4, 2, 8]

Largest value (8) is now at the end.

Pass 2:

  • Compare 3 and 5 → OK
  • Compare 5 and 4 → Swap → [3, 4, 5, 2, 8]
  • Compare 5 and 2 → Swap → [3, 4, 2, 5, 8]

Pass 3:

  • Compare 3 and 4 → OK
  • Compare 4 and 2 → Swap → [3, 2, 4, 5, 8]

Pass 4:

  • Compare 3 and 2 → Swap → [2, 3, 4, 5, 8]

Now the array is sorted.


5. Time and Space Complexity

CaseTime Complexity
Best CaseO(n) (already sorted, with optimization)
AverageO(n²)
Worst CaseO(n²)
  • Space Complexity: O(1) — in-place algorithm
  • Stable Sort: Yes (relative order of equal elements remains the same)

6. Bubble Sort in Dart (Flutter-Friendly)

Future<void> bubbleSort(List<int> array, Function(List<int>) onUpdate) async {
  int n = array.length;
  bool swapped;
  for (int i = 0; i < n; i++) {
    swapped = false;
    for (int j = 0; j < n - i - 1; j++) {
      if (array[j] > array[j + 1]) {
        int temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
        swapped = true;
      }
      onUpdate(List.from(array));
      await Future.delayed(Duration(milliseconds: 300));
    }
    if (!swapped) break;
  }
}

7. Visualization with Flutter + CustomPaint

Using Flutter’s CustomPaint, you can render each number as a vertical bar. With every step (triggered in onUpdate), the canvas repaints to reflect the new array state — enabling real-time animation of the sort.

Here’s a simplified Flutter implementation:

class BubbleSortVisualizer extends StatefulWidget {
  @override
  _BubbleSortVisualizerState createState() => _BubbleSortVisualizerState();
}

class _BubbleSortVisualizerState extends State<BubbleSortVisualizer> {
  List<int> _array = [5, 3, 8, 4, 2];

  void _startSort() async {
    await bubbleSort(_array, (newArray) {
      setState(() {
        _array = newArray;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: CustomPaint(
            painter: BarPainter(_array),
            child: Container(),
          ),
        ),
        ElevatedButton(
          onPressed: _startSort,
          child: Text("Start Sort"),
        ),
      ],
    );
  }
}

class BarPainter extends CustomPainter {
  final List<int> array;
  BarPainter(this.array);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blueAccent
      ..style = PaintingStyle.fill;

    final barWidth = size.width / array.length;
    final maxVal = array.reduce(max).toDouble();

    for (int i = 0; i < array.length; i++) {
      final barHeight = size.height * (array[i] / maxVal);
      final rect = Rect.fromLTWH(
        i * barWidth,
        size.height - barHeight,
        barWidth * 0.9,
        barHeight,
      );
      canvas.drawRect(rect, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

8. When Should You Use Bubble Sort?

You shouldn’t, unless:

  • You’re teaching or learning sorting basics.
  • You’re working with a trivially small dataset.
  • You need a stable, simple, and in-place sort.

9. Summary

Bubble Sort is intuitive but inefficient. It’s ideal for illustrating the logic of sorting but not recommended for serious applications with large data. Its real power is in helping you understand how sorting processes operate step by step.

Next up in our series: Selection Sort.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Lên đầu trang