Skip to content

Commit 3884cad

Browse files
committed
update example
1 parent 4b1cd41 commit 3884cad

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

example/top_sort.dart

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import 'dart:math';
2+
3+
import 'package:flutter/foundation.dart';
4+
import 'package:flutter/material.dart';
5+
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
6+
7+
import 'custom_app_bar.dart';
8+
9+
class OpenGrammarExample extends StatelessWidget {
10+
const OpenGrammarExample({Key? key}) : super(key: key);
11+
12+
@override
13+
Widget build(BuildContext context) {
14+
return Scaffold(
15+
appBar: const CustomAppBar(
16+
title: 'Open Grammar',
17+
codePath: 'example/n_grammar.dart',
18+
),
19+
body: ConstraintLayout().open(() {
20+
GestureDetector(
21+
child: Container(
22+
color: Colors.red,
23+
),
24+
onTap: () {
25+
Random random = Random();
26+
var arr = [
27+
for (int i = 0; i < 10000000; i++) random.nextInt(4294967296)
28+
];
29+
List copy = List.of(arr);
30+
Stopwatch stopwatch = Stopwatch()..start();
31+
topSort(arr);
32+
print("top sort time usage = ${stopwatch.elapsedMicroseconds}");
33+
stopwatch = Stopwatch()..start();
34+
copy.sort();
35+
print(
36+
"quick sort time usage = ${stopwatch.elapsedMicroseconds} ${listEquals(arr, copy)}");
37+
},
38+
).applyConstraint(
39+
size: 200,
40+
centerTo: parent,
41+
);
42+
}),
43+
);
44+
}
45+
}
46+
47+
void topSort(List<int> list) {
48+
int sum = 0;
49+
for (var element in list) {
50+
sum += element;
51+
}
52+
int slot;
53+
List<List<int>?> bucket = List.filled(list.length + 1, null);
54+
for (final element in list) {
55+
slot = ((element / sum) * list.length).toInt();
56+
if (slot < 0) {
57+
slot = 0;
58+
}
59+
if (bucket[slot] == null) {
60+
bucket[slot] = [];
61+
}
62+
bucket[slot]!.add(element);
63+
}
64+
int compare(int left, int right) {
65+
return left - right;
66+
}
67+
68+
int index = 0;
69+
for (final element in bucket) {
70+
if (element != null) {
71+
if (element.length > 1) {
72+
element.sort(compare);
73+
}
74+
if (element.isNotEmpty) {
75+
for (final element in element) {
76+
list[index] = element;
77+
index++;
78+
}
79+
}
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)