Skip to content

Commit bad9314

Browse files
committed
fix overflow bug
1 parent 53958a4 commit bad9314

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

example/chen_sort.dart

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ class ChenSortExample extends StatefulWidget {
1414
State createState() => ChenSortExampleState();
1515
}
1616

17+
int intMaxValue = 9223372036854775807;
18+
int intMinValue = -9223372036854775808;
19+
1720
class ChenSortExampleState extends State<ChenSortExample> {
1821
int defaultNumberCount = 100000;
1922
late TextEditingController numberCountController =
@@ -99,9 +102,14 @@ class ChenSortExampleState extends State<ChenSortExample> {
99102

100103
String compareSort(int numbers) {
101104
Random random = Random();
102-
var arr = [
103-
for (int i = 0; i < numbers; i++) -2 ^ 63 + random.nextInt(2 ^ 63)
104-
];
105+
List<int> arr = [];
106+
for (int i = 0; i < numbers; i++) {
107+
if (random.nextBool()) {
108+
arr.add(random.nextInt(1 << 32));
109+
} else {
110+
arr.add(-random.nextInt(1 << 32));
111+
}
112+
}
105113
List copy = List.of(arr);
106114
Stopwatch stopwatch = Stopwatch()..start();
107115
stopwatch.reset();
@@ -152,7 +160,7 @@ void chenSort(List<int> list) {
152160
/// and the maximum and minimum values.
153161
154162
/// Overflow detection
155-
BigInt range = BigInt.from(maxValue - minValue);
163+
BigInt range = BigInt.from(maxValue) - BigInt.from(minValue);
156164
if (BigInt.from(range.toInt()) == range) {
157165
int range = maxValue - minValue;
158166
double factor = maxBucketIndex / range;
@@ -167,7 +175,7 @@ void chenSort(List<int> list) {
167175
} else {
168176
/// Overflowed(positive minus negative)
169177
int positiveRange = maxValue;
170-
int negativeRange = -minValue - 1;
178+
int negativeRange = -1 - minValue;
171179
int positiveStartBucketIndex = maxBucketIndex ~/ 2 + 1;
172180
int positiveBucketLength = maxBucketIndex - positiveStartBucketIndex;
173181
int negativeBucketLength = positiveStartBucketIndex - 1;

0 commit comments

Comments
 (0)