Skip to content

Instantly share code, notes, and snippets.

@dmtrs
Created May 12, 2018 09:21
Show Gist options
  • Save dmtrs/3d7673fe8b4da85c388bb6accdc41022 to your computer and use it in GitHub Desktop.
Save dmtrs/3d7673fe8b4da85c388bb6accdc41022 to your computer and use it in GitHub Desktop.
Supercollider merge sort
(
var mergeSort = { |arr|
var merge = {|head, tail|
var i = 0;
var j = 0;
var k = head.size + tail.size;
head = head.add(0xfffffff);
tail = tail.add(0xffffff);
k.collect({
var h = head[i];
var t = tail[j];
if ( h > t ) {
j = j + 1;
t;
} {
i = i + 1;
h;
};
});
};
var mergeSortInternal = { |arr|
if (arr.size > 1, {
var q = (arr.size/2).asInt;
arr = merge.(mergeSortInternal.(arr[0..(q-1)]), mergeSortInternal.(arr[q..]));
});
arr;
};
mergeSortInternal.(arr)
};
var start, end;
var unsorted = (0..2000).scramble;
// run mergeSort vs sort for same scrambled array
start = Main.elapsedTime;
mergeSort.(unsorted);
end = Main.elapsedTime;
("mergeSort: " ++ ((end-start)*1000) ++ "ms").postln;
start = Main.elapsedTime;
unsorted.sort();
end = Main.elapsedTime;
("sort: " ++ ((end-start)*1000) ++ "ms").postln;
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment