Skip to content

Instantly share code, notes, and snippets.

@tomspilman
Created January 6, 2019 21:26
Show Gist options
  • Save tomspilman/f942219cd74209b66b660009222dab02 to your computer and use it in GitHub Desktop.
Save tomspilman/f942219cd74209b66b660009222dab02 to your computer and use it in GitHub Desktop.
private SpriteBatchItem[] _leftArray;
private SpriteBatchItem[] _rightArray;
private void MergeSort(SpriteBatchItem[] input, int left, int right)
{
if (left >= right)
return;
var middle = (left + right) / 2;
MergeSort(input, left, middle);
MergeSort(input, middle + 1, right);
var leftCount = middle - left + 1;
if (_leftArray == null || _leftArray.Length < leftCount)
_leftArray = new SpriteBatchItem[leftCount];
var rightCount = right - middle;
if (_rightArray == null || _rightArray.Length < rightCount)
_rightArray = new SpriteBatchItem[rightCount];
Array.Copy(input, left, _leftArray, 0, leftCount);
Array.Copy(input, middle + 1, _rightArray, 0, rightCount);
var i = 0;
var j = 0;
for (var k = left; k < right + 1; k++)
{
if (i == leftCount)
{
input[k] = _rightArray[j];
j++;
}
else if (j == rightCount)
{
input[k] = _leftArray[i];
i++;
}
else if (_leftArray[i].SortKey > _rightArray[j].SortKey)
{
input[k] = _rightArray[j];
j++;
}
else
{
input[k] = _leftArray[i];
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment