Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(337)

Side by Side Diff: pkg/collection_helpers/lib/algorithms.dart

Issue 23567044: Add collection-helpers library. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Addressed some comments. Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 /**
6 * Operations on collections.
7 */
8 library dart.collection_helper.algorithms;
9
10 import "dart:math" show Random;
11
12 /** Version of [binarySearch] optimized for comparable keys */
13 int _comparableBinarySearch(List<Comparable> list, Comparable key,
14 bool location) {
15 int min = 0;
16 int max = list.length;
17 while (min < max) {
18 int mid = min + ((max - min) ~/ 2);
19 var element = list[mid];
20 int comp = element.compareTo(key);
21 if (comp == 0) return mid;
22 if (comp < 0) {
23 min = mid + 1;
24 } else {
25 max = mid;
26 }
27 }
28 if (location) return min;
29 return -1;
30 }
31
32 /**
33 * Returns the position of the [key] in [sortedList], if it is there.
34 *
35 * If the list isn't sorted according to the [compare] function, the result
36 * is unpredicatable.
37 *
38 * If [compare] is omitted, it defaults to calling [Comparable.compareTo] on
39 * the objects.
40 *
41 * Returns -1 if [key] is not in the list by default.
42 * If [location] is true, instead returns the index where [key] would have
43 * been. That is, where inserting the key at the returned position would keep
44 * the list sorted.
45 */
46 int binarySearch(List sortedList, var key,
47 { int compare(var a, var b),
48 bool location: false
Lasse Reichstein Nielsen 2013/10/03 11:17:33 I'll remove the location parameter and just return
49 }) {
50 if (compare == null) {
51 return _comparableBinarySearch(sortedList, key, location);
52 }
53 int min = 0;
54 int max = sortedList.length;
55 while (min < max) {
56 int mid = min + ((max - min) ~/ 2);
57 var element = sortedList[mid];
58 int comp = compare(element, key);
59 if (comp == 0) return mid;
60 if (comp < 0) {
61 min = mid + 1;
62 } else {
63 max = mid;
64 }
65 }
66 if (location) return max;
67 return -1;
68 }
69
70
71 /**
72 * Shuffles a list randomly.
73 *
74 * A sub-range of a list can be shuffled by providing [start] and [end].319
75 */
76 void shuffle(List list, [int start = 0, int end = null]) {
77 Random random = new Random();
78 if (end == null) end = list.length;
79 int length = end - start;
80 while (length > 1) {
81 int pos = random.nextInt(length);
82 var tmp1 = list[start + pos];
83 var tmp2 = list[start + length - 1];
84 list[start + length - 1] = tmp1;
85 list[start + pos] = tmp2;
86 length--;
87 }
88 }
89
90
91 /**
92 * Reverses a list, or a part of a list, in-place.
93 */
94 void reverse(List list, [int start = 0, int end = null]) {
95 if (end == null) end = list.length;
96 _reverse(list, start, end);
97 }
98
99 // Internal helper function that assumes valid arguments.
100 void _reverse(List list, int start, int end) {
101 for (int i = start, j = end - 1; i < j; i++, j--) {
102 var tmp = list[i];
103 list[i] = list[j];
104 list[j] = tmp;
105 }
106 }
107
108 /**
109 * Sort a list using insertion sort.
110 *
111 * Insertion sort is a simple sorting algorithm. For `n` elements it does on
112 * the order of `n * log(n)` comparisons but up to `n` squared moves. The
113 * sorting is performed in-place, without using extra memory.
114 *
115 * For short lists the many moves have less impact than the simple algorithm,
116 * and it is often the favored sorting algorithm for short lists.
117 *
118 * This insertion sort is stable: Equal elements end up in the same order
119 * as they started in.
120 */
121 void insertionSort(List list,
122 { int compare(a, b),
123 int start: 0,
124 int end: null }) {
125 // If the same method could have both positional and named optional
126 // parameters, this should be (list, [start, end], {compare}).
127 if (end == null) end = list.length;
128 if (compare == null) compare = Comparable.compare;
129 _insertionSort(list, compare, start, end, start + 1);
130 }
131
132 /**
133 * Internal helper function that assumes arguments correct.
134 *
135 * Assumes that the elements up to [sortedUntil] (not inclusive) are
136 * already sorted. The [sortedUntil] values should always be at least
137 * `start + 1`.
138 */
139 void _insertionSort(List list, int compare(a, b), int start, int end,
140 int sortedUntil) {
141 for (int pos = sortedUntil; pos < end; pos++) {
142 int min = start;
143 int max = pos;
144 var element = list[pos];
145 while (min < max) {
146 int mid = min + ((max - min) ~/ 2);
147 int comparison = compare(element, list[mid]);
148 if (comparison < 0) {
149 max = mid;
150 } else {
151 min = mid + 1;
152 }
153 }
154 list.setRange(min + 1, pos + 1, list, min);
155 list[min] = element;
156 }
157 }
158
159 /** Limit below which merge sort defaults to insertion sort. */
160 const int _MERGE_SORT_LIMIT = 32;
161
162 /**
163 * Sorts a list, or a range of a list, using the merge sort algorithm.
164 *
165 * Merge-sorting works by splitting the job into two parts, sorting each
166 * recursively, and then merging the two sorted parts.
167 *
168 * This takes on the order of `n * log(n)` comparisons and moves to sort
169 * `n` elements, but requires extra space of about the same size as the list
170 * being sorted.
171 *
172 * This merge sort is stable: Equal elements end up in the same order
173 * as they started in.
174 */
175 void mergeSort(List list, {int start: 0, int end: null, int compare(a, b)}) {
176 if (end == null) end = list.length;
177 if (compare == null) compare = Comparable.compare;
178 int length = end - start;
179 if (length < 2) return;
180 if (length < _MERGE_SORT_LIMIT) {
181 _insertionSort(list, compare, start, end, start + 1);
182 return;
183 }
184 // Special case the first split instead of directly calling
185 // _mergeSort, because the _mergeSort requires its target to
186 // be different from its source, and it requires extra space
187 // of the same size as the list to sort.
188 // This split allows us to have only half as much extra space,
189 // and it ends up in the original place.
190 int middle = start + ((end - start) ~/ 2);
191 int firstLength = middle - start;
192 int secondLength = end - middle;
193 // secondLength is always the same as firstLength, or one greater.
194 List scratchSpace = new List(secondLength);
195 _mergeSort(list, compare, middle, end, scratchSpace, 0);
196 int firstTarget = end - firstLength;
197 _mergeSort(list, compare, start, middle, list, firstTarget);
198 _merge(compare,
199 list, firstTarget, end,
200 scratchSpace, 0, secondLength,
201 list, start);
202 }
203
204 /**
205 * Performs an insertion sort into a potentially different list than the
206 * one containing the original values.
207 *
208 * It will work in-place as well.
209 */
210 void _movingInsertionSort(List list, int compare(a, b), int start, int end,
211 List target, int targetOffset) {
212 int length = end - start;
213 if (length == 0) return;
214 target[targetOffset] = list[start];
215 for (int i = 1; i < length; i++) {
216 var element = list[start + i];
217 int min = targetOffset;
218 int max = targetOffset + i;
219 while (min < max) {
220 int mid = min + ((max - min) ~/ 2);
221 if (compare(element, target[mid]) < 0) {
222 max = mid;
223 } else {
224 min = mid + 1;
225 }
226 }
227 target.setRange(min + 1, targetOffset + i + 1,
228 target, min);
229 target[min] = element;
230 }
231 }
232
233 /**
234 * Sorts [list] from [start] to [end] into [target] at [targetOffset].
235 *
236 * The `target` list must be able to contain the range from `start` to `end`
237 * after `targetOffset`.
238 *
239 * Allows target to be the same list as [list], as long as it's not
240 * overlapping the `start..end` range.
241 */
242 void _mergeSort(List list, int compare(a, b), int start, int end,
243 List target, int targetOffset) {
244 int length = end - start;
245 if (length < _MERGE_SORT_LIMIT) {
246 _movingInsertionSort(list, compare, start, end, target, targetOffset);
247 return;
248 }
249 int middle = start + (length ~/ 2);
250 int firstLength = middle - start;
251 int secondLength = end - middle;
252 // Here secondLength >= firstLength (differs by at most one).
253 int targetMiddle = targetOffset + firstLength;
254 // Sort the second half into the end of the target area.
255 _mergeSort(list, compare, middle, end,
256 target, targetMiddle);
257 // Sort the first half into the end of the source area.
258 _mergeSort(list, compare, start, middle,
259 list, middle);
260 // Merge the two parts into the target area.
261 _merge(compare,
262 list, middle, middle + firstLength,
263 target, targetMiddle, targetMiddle + secondLength,
264 target, targetOffset);
265 }
266
267 /**
268 * Merges two lists into a target list.
269 *
270 * One of the input lists may be positioned at the end of the target
271 * list.
272 *
273 * For equal object, elements from [firstList] are always preferred.
274 * This allows the merge to be stable if the first list contains elements
275 * that started out earlier than the ones in [secondList]
276 */
277 void _merge(int compare(a, b),
278 List firstList, int firstStart, int firstEnd,
279 List secondList, int secondStart, int secondEnd,
280 List target, int targetOffset) {
281 // No empty lists reaches here.
282 assert(firstStart < firstEnd);
283 assert(secondStart < secondEnd);
284 int cursor1 = firstStart;
285 int cursor2 = secondStart;
286 var firstElement = firstList[cursor1++];
287 var secondElement = secondList[cursor2++];
288 while (true) {
289 if (compare(firstElement, secondElement) <= 0) {
290 target[targetOffset++] = firstElement;
291 if (cursor1 == firstEnd) break; // Flushing second list after loop.
292 firstElement = firstList[cursor1++];
293 } else {
294 target[targetOffset++] = secondElement;
295 if (cursor2 != secondEnd) {
296 secondElement = secondList[cursor2++];
297 continue;
298 }
299 // Second list empties first. Flushing first list here.
300 target[targetOffset++] = firstElement;
301 target.setRange(targetOffset, targetOffset + (firstEnd - cursor1),
302 firstList, cursor1);
303 return;
304 }
305 }
306 // First list empties first. Reached by break above.
307 target[targetOffset++] = secondElement;
308 target.setRange(targetOffset, targetOffset + (secondEnd - cursor2),
309 secondList, cursor2);
310 }
OLDNEW
« no previous file with comments | « no previous file | pkg/collection_helpers/lib/all.dart » ('j') | pkg/collection_helpers/lib/equality.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698