forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BeadSort.dart
89 lines (82 loc) · 1.71 KB
/
BeadSort.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
Sorting algorithm that is also called Gravity Sort. It can be visualised as
beads of an abacus falling under the influence fo gravity with the row having
the most beads is at the bottom and least is at top.
*/
import 'dart:io';
enum SortStatus { BEAD, BLANK, NULL }
// function that implements bead sort
List beadSort(List arr) {
// finding max item to decide width of the abacus
int max = 0;
for (int item in arr) {
if (item > max) {
max = item;
}
}
// setting the abacus
List abacus = List.generate(arr.length, (index) => new List.filled(max, SortStatus.NULL),
growable: false);
List level = [];
for (int i = 0; i < max; i++) {
level.add(0);
for (int j = 0; j < arr.length; j++) {
abacus[j][i] = SortStatus.BLANK;
}
}
// adding the beads
for (int item in arr) {
for (int j = 0; item > 0; j++, item--) {
abacus[level[j]++][j] = SortStatus.BEAD;
}
}
// counting beads
for (int i = 0; i < arr.length; i++) {
int number = 0;
for (int j = 0;
j < max && abacus[arr.length - 1 - i][j] == SortStatus.BEAD;
j++) {
number++;
}
arr[i] = number;
}
return arr;
}
// main function, entry point of the program
void main() {
print("Enter the size of list:");
int size = int.parse(stdin.readLineSync()!);
List arr = [];
print("Enter the numbers:");
for (int i = 0; i < size; i++) {
arr.add(int.parse(stdin.readLineSync()!));
}
// sorting
arr = beadSort(arr);
print("Sorted list:");
for (int i = 0; i < size; i++) {
print(arr[i]);
}
}
/**
Enter the size of list:
6
Enter the numbers:
5
0
2
1
4
3
Enter number of buckets:
5
Sorted list:
0
1
2
3
4
5
Time Complexity: O(n)
Space Complexity: O(n^2)
*/