Created
April 24, 2012 11:52
-
-
Save iggymacd/2479067 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} | |
Temp t = new Temp(); | |
print('in mergeSort...' + t.sample); | |
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])); | |
} | |
class Temp{ | |
String sample; | |
Temp(){ | |
sample = 'waiting'; | |
} | |
} | |
void main() { | |
var arr=[1,5,2,7,3,9,4,6,8]; | |
print(arr); | |
isolate.spawnFunction(mergeSortIsolate).call(arr).then(print); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment