How to Implement the Bubble Sort Algorithm in Flutter.

We’ll explore the bubble sort algorithm in Flutter and demonstrate how to create a visualizer for it using Flutter.

Bubble sorting is one of the simplest sorting algorithms in computer science. It’s often taught in introductory computer science courses due to its straightforward nature. This visualizer will help you understand the step-by-step process of the bubble sort algorithm in Flutter more interactively and engagingly.

bubble sort algorithm in Flutter

What is the bubble sort algorithm in Flutter?

Bubble sort is a comparison-based algorithm where each pair of adjacent elements is compared, and the elements are swapped if they are in the wrong order. This process repeats until the list is sorted. Despite its simplicity, bubble sort is not very efficient for large datasets due to its O(n^2) time complexity.

Key Concepts of Bubble Sort:

  1. Comparison: Each pair of adjacent elements is compared.
  2. Swap: Elements are swapped if they are not in order.
  3. Passes: Multiple passes are made through the list until no swaps are needed.

Bubble sort algorithm in Flutter

First, ensure you have Flutter installed on your system. If not, follow the official Flutter installation guide to set it up.

Creating the Bubble Sort Visualizer:

Setting Up the Project

  • Open your terminal and run flutter create bubble_sort_visualizer.
  • Navigate to the project directory with cd bubble_sort_visualizer.

Main Dart File

Replace the content of lib/main.dart with the following code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bubble Sort Visualizer',
      home: BubbleSortScreen(),
    );
  }
}

class BubbleSortScreen extends StatefulWidget {
  @override
  _BubbleSortScreenState createState() => _BubbleSortScreenState();
}

class _BubbleSortScreenState extends State<BubbleSortScreen> {
  List<int> _numbers = [6, 2, 8, 4, 1, 9, 7, 5, 3];
  bool _sorting = false;

  Future<void> _bubbleSort() async {
    setState(() {
      _sorting = true;
    });

    List<int> sortedList = List.from(_numbers);

    for (int i = 0; i < sortedList.length - 1; i++) {
      for (int j = 0; j < sortedList.length - i - 1; j++) {
        if (sortedList[j] > sortedList[j + 1]) {
          // Swap numbers
          int temp = sortedList[j];
          sortedList[j] = sortedList[j + 1];
          sortedList[j + 1] = temp;

          // Update UI after each swap
          setState(() {
            _numbers = List.from(sortedList);
          });

          await Future.delayed(Duration(milliseconds: 200));
        }
      }
    }

    setState(() {
      _sorting = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bubble Sort Visualizer'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: _numbers
                  .map((number) => Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: Container(
                          height: 26,
                          width: 26,
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Center(
                            child: Text(
                              number.toString(),
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ),
          ElevatedButton(
            onPressed: _sorting ? null : _bubbleSort,
            child: Text('Sort'),
          ),
          SizedBox(height: 20),
        ],
      ),
    );
  }
}

Understanding the Code

  • Main Method: The main() function runs the MyApp class, which sets up a basic Material app with a BubbleSortScreen.
  • Stateful Widget: This BubbleSortScreen is a stateful widget that manages the list of numbers and the sorting state.
  • Bubble Sort Algorithm: The _bubbleSort the method contains the bubble sort logic. It uses nested loops to iterate through the list and swap elements if needed. The UI updates after each swap with a slight delay for visualization.

Running the App

  • Run flutter run in your terminal.
  • You should see a screen with a row of numbers and a “Sort” button. Pressing the button will start the bubble sort visualization.

Output:

Screenshot 2024 07 26 at 22.09.23

Also Read:

Conclusion

In this blog post, we’ve covered the basic concept of bubble sort and implemented a visualizer using Flutter. This interactive tool helps illustrate how bubble sort works step by step. While bubble sort may not be the most efficient algorithm for large datasets, it’s an excellent way to understand sorting algorithms’ core principles.

Share:
Ambika Dulal

Ambika Dulal is a Flutter Developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu