#include "petscsys.h" PetscErrorCode PetscTimSortWithArray(PetscInt n, void *arr, size_t asize, void *barr, size_t bsize, int (*cmp)(const void *, const void *, void *), void *ctx)Not Collective
n | - number of values | |
arr | - array to be sorted | |
asize | - size in bytes of the datatype held in arr | |
barr | - array to be reordered | |
asize | - size in bytes of the datatype held in barr | |
cmp | - function pointer to comparison function | |
ctx | - optional context to be passed to comparison function, NULL if not needed |
arr | - sorted array | |
barr | - reordered array |
Timsort makes the assumption that input data is already likely partially ordered, or that it contains contiguous sections (termed 'runs') where the data is locally ordered (but not necessarily globally ordered). It therefore aims to select slices of the array in such a way that resulting mergesorts operate on near perfectly length-balanced arrays. To do so it repeatedly triggers attempts throughout to merge adjacent runs.
Should one run continuously "win" a comparison the algorithm begins the "gallop" phase. It will aggressively search the "winner" for the location of the "losers" next entry (and vice versa) to copy all preceding elements into place in bulk. However if the data is truly unordered (as is the case with random data) the immense gains possible from these searches are expected __not__ to repay their costs. While adjacent arrays are almost all nearly the same size, they likely all contain similar data.
int my_increasing_comparison_function(const void *left, const void *right, void *ctx) { my_type l = *(my_type *) left, r = *(my_type *) right; return (l < r) ? -1 : (l > r); }Note the context is unused here but you may use it to pass and subsequently access whatever information required inside the comparison function. The context pointer will unaltered except for any changes made inside the comparison function. Then pass the function
PetscTimSortWithArray(n, arr, sizeof(arr[0]), barr, sizeof(barr[0]), my_increasing_comparison_function, ctx)
subroutine CompareIntegers(left,right,ctx,result) implicit none PetscInt,intent(in) :: left, right type(UserCtx) :: ctx integer,intent(out) :: result if (left < right) then result = -1 else if (left == right) then result = 0 else result = 1 end if return end subroutine CompareIntegers