Skip to content

Instantly share code, notes, and snippets.

@adam-singer
Created March 14, 2012 06:08
Show Gist options
  • Save adam-singer/2034492 to your computer and use it in GitHub Desktop.
Save adam-singer/2034492 to your computer and use it in GitHub Desktop.
Merge Sort Isolate Example
#import('dart:isolate', prefix:'isolate');
List split(List numbers) {
int size = numbers.length;
int middleIndex = (size/2).floor().toInt();
var list1 = numbers.getRange(0, middleIndex);
var list2 = numbers.getRange(middleIndex, size-middleIndex);
return [list1, list2];
}
List merge(List a, List b) {
int i = 0;
int j = 0;
List result = [];
// These checks should not exist
if (a == null && b != null) { return b; }
if (b == null && a != null) { return a; }
if (a == null && b == null) { return []; }
while((i<a.length) && (j<b.length)) {
if (a[i] <= b[j]) {
result.add(a[i++]);
} else {
result.add(b[j++]);
}
}
if (i<a.length) {
result.addAll(a.getRange(i, a.length-i));
} else {
result.addAll(b.getRange(j, b.length-j));
}
return result;
}
mergeSortIsolate() {
isolate.port.receive((msg, reply) {
mergeSort(msg).then((m) {
reply.send(m);
isolate.port.close();
});
});
}
Future<List> mergeSort(List arr) {
if (arr.length == 0 || arr.length == 1) {
return new Future.immediate(arr);
}
var s = split(arr);
var w = Futures.wait([
isolate.spawnFunction(mergeSortIsolate).call(s[0]),
isolate.spawnFunction(mergeSortIsolate).call(s[1])]);
return w.transform((values) => merge(values[0], values[1]));
}
void main() {
var arr=[1,5,2,7,3,9,4,6,8];
print(arr);
isolate.spawnFunction(mergeSortIsolate).call(arr).then(print);
}
@adam-singer
Copy link
Author

Example of how to do a merge sort using dart:isolate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment