function mergeSort(array, comparator, userDefinedObject) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(array)) {
    throw new DeveloperError("array is required.");
  }
  if (!defined(comparator)) {
    throw new DeveloperError("comparator is required.");
  }
  //>>includeEnd('debug');

  const length = array.length;
  const scratchLength = Math.ceil(length * 0.5);

  // preallocate space in scratch arrays
  leftScratchArray.length = scratchLength;
  rightScratchArray.length = scratchLength;

  sort(array, comparator, userDefinedObject, 0, length - 1);

  // trim scratch arrays
  leftScratchArray.length = 0;
  rightScratchArray.length = 0;
}
A stable merge sort.

@function mergeSort
@param {Array} array The array to sort.
@param {mergeSortComparator} comparator The function to use to compare elements in the array.
@param {*} [userDefinedObject] Any item to pass as the third parameter to <code>comparator</code>.

@example
// Assume array contains BoundingSpheres in world coordinates.
// Sort them in ascending order of distance from the camera.
const position = camera.positionWC;
Cesium.mergeSort(array, function(a, b, position) {
    return Cesium.BoundingSphere.distanceSquaredTo(b, position) - Cesium.BoundingSphere.distanceSquaredTo(a, position);
}, position);