This repository has been archived on 2024-09-24. You can view files and clone it, but cannot push or open issues or pull requests.
Quicksort/lib/sorting.dart

117 lines
2.8 KiB
Dart
Raw Normal View History

2023-11-18 11:16:27 +01:00
import 'dart:math';
import 'package:flutter/material.dart';
class Sorting extends StatefulWidget {
const Sorting({super.key, required this.amount});
final int amount;
@override
State<Sorting> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<Sorting> {
bool _started = false;
final List<int> _arr = [];
@override
void initState() {
super.initState();
for (int i = 0; i < widget.amount; i++) {
_arr.add(Random().nextInt(100));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: Visibility(
visible: !_started,
child: FloatingActionButton(
onPressed: () {
setState(() {
_started = true;
});
quicksort(0, _arr.length - 1);
},
tooltip: 'Start Sorting!',
child: const Icon(Icons.play_arrow),
),
),
appBar: AppBar(
title: const Text("QuickSort"),
),
body: GridView.builder(
itemCount: _arr.length,
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemBuilder: (context, index) {
return Card(
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('${index + 1}:'),
),
Center(
child: Text(
_arr[index].toString(),
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
);
}),
);
}
Future<void> quicksort(int begin, int end) async {
final pivot = _arr.sublist(begin, end + 1).mean;
var left = begin;
var right = end;
while (true) {
while (_arr[left] < pivot) {
left++;
}
while (_arr[right] > pivot) {
right--;
}
if (left < right) {
await Future.delayed(const Duration(seconds: 2));
final temp = _arr[left];
setState(() {
_arr[left] = _arr[right];
_arr[right] = temp;
});
left++;
right--;
} else {
if (begin < left - 1) quicksort(begin, left - 1);
if (right + 1 < end) quicksort(right + 1, end);
break;
}
}
}
@override
void dispose() {
super.dispose();
}
}
extension Sum<int extends num> on List<int> {
int get sum => reduce((value, element) => value + element as int);
}
extension Mean<int extends num> on List<int> {
double get mean => sum / length;
}