|
| 1 | +import 'Student.dart'; |
| 2 | +import 'dart:math'; |
| 3 | + |
| 4 | +void main() { |
| 5 | + print("abcdefghijklmnopqrstuvwxyz".codeUnits); |
| 6 | + print("abcdefghijklmnopqrstuvwxyz".runes); |
| 7 | + print(String.fromCharCode("abcdefghijklmnopqrstuvwxyz".codeUnits[0])); |
| 8 | + print(String.fromCharCode("abcdefghijklmnopqrstuvwxyz".codeUnits[0])); |
| 9 | + Iterable<int>? string = [ |
| 10 | + 97, |
| 11 | + 98, |
| 12 | + 99, |
| 13 | + 100, |
| 14 | + 101, |
| 15 | + 102, |
| 16 | + 103, |
| 17 | + 104, |
| 18 | + 105, |
| 19 | + 106, |
| 20 | + 107, |
| 21 | + 108, |
| 22 | + 109, |
| 23 | + 110, |
| 24 | + 111, |
| 25 | + 112, |
| 26 | + 113, |
| 27 | + 114, |
| 28 | + 115, |
| 29 | + 116, |
| 30 | + 117, |
| 31 | + 118, |
| 32 | + 119, |
| 33 | + 120, |
| 34 | + 121, |
| 35 | + 122 |
| 36 | + ]; |
| 37 | + print(String.fromCharCodes(string, 0, 26)); |
| 38 | + |
| 39 | + int n = 26 * 26 * 26 * 26; |
| 40 | + |
| 41 | + List students = List.filled(n, Student, growable: true); |
| 42 | + int k = 0; |
| 43 | + Random rnd = new Random(); |
| 44 | + for (var c1 = 'a'.codeUnits[0]; c1 <= 'z'.codeUnits[0]; c1++) |
| 45 | + for (var c2 = 'a'.codeUnits[0]; c2 <= 'z'.codeUnits[0]; c2++) |
| 46 | + for (var c3 = 'a'.codeUnits[0]; c3 <= 'z'.codeUnits[0]; c3++) |
| 47 | + for (var c4 = 'a'.codeUnits[0]; c4 <= 'z'.codeUnits[0]; c4++) { |
| 48 | + students[k] = new Student( |
| 49 | + "${String.fromCharCode(c1)} + ${String.fromCharCode(c2)} + ${String.fromCharCode(c3)} + ${String.fromCharCode(c4)}", |
| 50 | + rnd.nextInt(101)); |
| 51 | + k++; |
| 52 | + } |
| 53 | + |
| 54 | + // 计数排序过程 |
| 55 | + int R = 101; |
| 56 | + |
| 57 | + // O(n) |
| 58 | + List cnt = List.filled(R, int, growable: true); |
| 59 | + for (Student student in students) cnt[student.getScore()!]++; |
| 60 | + |
| 61 | + // O(R) |
| 62 | + List index = List.filled(R + 1, int, growable: true); |
| 63 | + for (int i = 0; i < R; i++) index[i + 1] = index[i] + cnt[i]; |
| 64 | + |
| 65 | + // O(n) |
| 66 | + List temp = List.filled(n, Student, growable: true); |
| 67 | + for (Student student in students) { |
| 68 | + temp[index[student.getScore()!]] = student; |
| 69 | + index[student.getScore()!]++; |
| 70 | + } |
| 71 | + |
| 72 | + // O(n) |
| 73 | + for (int i = 0; i < n; i++) students[i] = temp[i]; |
| 74 | + |
| 75 | + // O(n + R) |
| 76 | + |
| 77 | + // 验证计数排序算法 |
| 78 | + for (int i = 1; i < n; i++) { |
| 79 | + if (students[i - 1].getScore() > students[i].getScore()) |
| 80 | + throw new Exception("Sort failed"); |
| 81 | + |
| 82 | + if (students[i - 1].getScore() == students[i].getScore()) { |
| 83 | + if (students[i - 1].getName().compareTo(students[i].getName()) >= 0) |
| 84 | + throw new Exception("Non-Stable counting sort!"); |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments