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.
Table of Contents
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:
- Comparison: Each pair of adjacent elements is compared.
- Swap: Elements are swapped if they are not in order.
- 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 theMyApp
class, which sets up a basic Material app with aBubbleSortScreen
. - 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:
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.