⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sort.texi

📁 开放gsl矩阵运算
💻 TEXI
字号:
@cindex sorting @cindex heapsortThis chapter describes functions for sorting data, both directly andindirectly (using an index).  All the functions use the @dfn{heapsort}algorithm.  Heapsort is an @math{O(N \log N)} algorithm which operatesin-place.  It does not require any additional storage and providesconsistent performance.  The running time for its worst-case (ordereddata)  is not significantly longer than the average and bestcases.  Note that the heapsort algorithm does not preserve the relativeordering of equal elements --- it is an @dfn{unstable} sort.  Howeverthe resulting order of equal elements will be consistent acrossdifferent platforms when using these functions.@menu* Sorting objects::             * Sorting vectors::             * Selecting the k-th smallest or largest elements::  * Computing the rank::          * Sorting Examples::            * Sorting References and Further Reading::  @end menu@node Sorting objects@section Sorting objectsThe following function provides a simple alternative to the standardlibrary function @code{qsort}.  It is intended for systems lacking@code{qsort}, not as a replacement for it.  The function @code{qsort}should be used whenever possible, as it will be faster and can providestable ordering of equal elements.  Documentation for @code{qsort} isavailable in the @cite{GNU C Library Reference Manual}.The functions described in this section are defined in the header file@file{gsl_heapsort.h}.@cindex comparison functions, definition@deftypefun void gsl_heapsort (void * @var{array}, size_t @var{count}, size_t @var{size}, gsl_comparison_fn_t @var{compare})This function sorts the @var{count} elements of the array @var{array},each of size @var{size}, into ascending order using the comparisonfunction @var{compare}.  The type of the comparison function is defined by,@exampleint (*gsl_comparison_fn_t) (const void * a,                            const void * b)@end example@noindentA comparison function should return a negative integer if the firstargument is less than the second argument, @code{0} if the two argumentsare equal and a positive integer if the first argument is greater thanthe second argument.For example, the following function can be used to sort doubles intoascending numerical order.@exampleintcompare_doubles (const double * a,                 const double * b)@{    return (int) (*a - *b);@}@end example@noindentThe appropriate function call to perform the sort is,@examplegsl_heapsort (array, count, sizeof(double),               compare_doubles);@end exampleNote that unlike @code{qsort} the heapsort algorithm cannot be made intoa stable sort by pointer arithmetic.  The trick of comparing pointers forequal elements in the comparison function does not work for the heapsortalgorithm.  The heapsort algorithm performs an internal rearrangement ofthe data which destroys its initial ordering.@end deftypefun@cindex indirect sorting@deftypefun int gsl_heapsort_index (size_t * p, const void * @var{array}, size_t @var{count}, size_t @var{size}, gsl_comparison_fn_t @var{compare})This function indirectly sorts the @var{count} elements of the array@var{array}, each of size @var{size}, into ascending order using thecomparison function @var{compare}.  The resulting permutation is storedin @var{p}, an array of length @var{n}.  The elements of @var{p} give theindex of the array element which would have been stored in that positionif the array had been sorted in place.  The first element of @var{p}gives the index of the least element in @var{array}, and the lastelement of @var{p} gives the index of the greatest element in@var{array}.  The array itself is not changed.@end deftypefun@node Sorting vectors@section Sorting vectorsThe following functions will sort the elements of an array or vector,either directly or indirectly.  They are defined for all real and integertypes using the normal suffix rules.  For example, the @code{float}versions of the array functions are @code{gsl_sort_float} and@code{gsl_sort_float_index}.  The corresponding vector functions are@code{gsl_sort_vector_float} and @code{gsl_sort_vector_float_index}.  Theprototypes are available in the header files @file{gsl_sort_float.h}@file{gsl_sort_vector_float.h}.  The complete set of prototypes can beincluded using the header files @file{gsl_sort.h} and@file{gsl_sort_vector.h}.There are no functions for sorting complex arrays or vectors, since theordering of complex numbers is not uniquely defined.  To sort a complexvector by magnitude compute a real vector containing the the magnitudesof the complex elements, and sort this vector indirectly.  The resultingindex gives the appropriate ordering of the original complex vector.@cindex sorting vector elements@cindex vector, sorting elements of@deftypefun void gsl_sort (double * @var{data}, size_t @var{stride}, size_t @var{n})This function sorts the @var{n} elements of the array @var{data} withstride @var{stride} into ascending numerical order.@end deftypefun@deftypefun void gsl_sort_vector (gsl_vector * @var{v})This function sorts the elements of the vector @var{v} into ascendingnumerical order.@end deftypefun@cindex indirect sorting, of vector elements@deftypefun int gsl_sort_index (size_t * @var{p}, const double * @var{data}, size_t @var{stride}, size_t @var{n})This function indirectly sorts the @var{n} elements of the array@var{data} with stride @var{stride} into ascending order, storing theresulting permutation in @var{p}.  The array @var{p} must be allocated toa sufficient length to store the @var{n} elements of the permutation.The elements of @var{p} give the index of the array element which wouldhave been stored in that position if the array had been sorted in place.The array @var{data} is not changed.@end deftypefun@deftypefun int gsl_sort_vector_index (gsl_permutation * @var{p}, const gsl_vector * @var{v})This function indirectly sorts the elements of the vector @var{v} intoascending order, storing the resulting permutation in @var{p}.  Theelements of @var{p} give the index of the vector element which wouldhave been stored in that position if the vector had been sorted inplace.  The first element of @var{p} gives the index of the least elementin @var{v}, and the last element of @var{p} gives the index of thegreatest element in @var{v}.  The vector @var{v} is not changed.@end deftypefun@node Selecting the k-th smallest or largest elements@section Selecting the k-th smallest or largest elementsThe functions described in this section select the @math{k}-th smallestor largest elements of a data set of size @math{N}.  The routines use an@math{O(kN)} direct insertion algorithm which is suited to subsets thatare small compared with the total size of the dataset. For example, theroutines are useful for selecting the 10 largest values from one milliondata points, but not for selecting the largest 100,000 values.  If thesubset is a significant part of the total dataset it may be fasterto sort all the elements of the dataset directly with an @math{O(N \logN)} algorithm and obtain the smallest or largest values that way.@deftypefun void gsl_sort_smallest (double * @var{dest}, size_t @var{k}, const double * @var{src}, size_t @var{stride}, size_t @var{n})This function copies the @var{k}-th smallest elements of the array@var{src}, of size @var{n} and stride @var{stride}, in ascendingnumerical order in @var{dest}.  The size of the subset @var{k} must beless than or equal to @var{n}.  The data @var{src} is not modified bythis operation.@end deftypefun@deftypefun void gsl_sort_largest (double * @var{dest}, size_t @var{k}, const double * @var{src}, size_t @var{stride}, size_t @var{n})This function copies the @var{k}-th largest elements of the array@var{src}, of size @var{n} and stride @var{stride}, in descendingnumerical order in @var{dest}. The size of the subset @var{k} must beless than or equal to @var{n}. The data @var{src} is not modified bythis operation.@end deftypefun@deftypefun void gsl_sort_vector_smallest (double * @var{dest}, size_t @var{k}, const gsl_vector * @var{v})@deftypefunx void gsl_sort_vector_largest (double * @var{dest}, size_t @var{k}, const gsl_vector * @var{v})These functions copy the @var{k}-th smallest or largest elements of thevector @var{v} into the array @var{dest}. The size of the subset @var{k}must be less than or equal to the length of the vector @var{v}.@end deftypefunThe following functions find the indices of the @math{k}-th smallest orlargest elements of a dataset,@deftypefun void gsl_sort_smallest_index (size_t * @var{p}, size_t @var{k}, const double * @var{src}, size_t @var{stride}, size_t @var{n})This function stores the indices of the @var{k}-th smallest elements ofthe array @var{src}, of size @var{n} and stride @var{stride}, in thearray @var{p}.  The indices are chosen so that the corresponding data isin ascending numerical order.  The size of the subset @var{k} must beless than or equal to @var{n}. The data @var{src} is not modified bythis operation.@end deftypefun@deftypefun void gsl_sort_largest_index (size_t * @var{p}, size_t @var{k}, const double * @var{src}, size_t @var{stride}, size_t @var{n})This function stores the indices of the @var{k}-th largest elements ofthe array @var{src}, of size @var{n} and stride @var{stride}, in thearray @var{p}.  The indices are chosen so that the corresponding data isin descending numerical order.  The size of the subset @var{k} must beless than or equal to @var{n}. The data @var{src} is not modified bythis operation.@end deftypefun@deftypefun void gsl_sort_vector_smallest_index (size_t * @var{p}, size_t @var{k}, const gsl_vector * @var{v})@deftypefunx void gsl_sort_vector_largest_index (size_t * @var{p}, size_t @var{k}, const gsl_vector * @var{v})These functions store the indices of @var{k}-th smallest or largestelements of the vector @var{v} in the array @var{p}. The size of thesubset @var{k} must be less than or equal to the length of the vector@var{v}.@end deftypefun@node Computing the rank@section Computing the rankThe @dfn{rank} of an element is its order in the sorted data.  The rankis the inverse of the index permutation, @var{p}.  It can be computedusing the following algorithm,@examplefor (i = 0; i < p->size; i++) @{    size_t pi = p->data[i];    rank->data[pi] = i;@}@end example@noindentThis can be computed directly from the function@code{gsl_permutation_invert(rank,p)}.The following function will print the rank of each element of the vector@var{v},@examplevoidprint_rank (gsl_vector * v)@{  size_t i;  size_t n = v->size;  gsl_permutation * perm = gsl_permutation_alloc(n);  gsl_permutation * rank = gsl_permutation_alloc(n);  gsl_sort_vector_index (perm, v);  gsl_permutation_invert (rank, perm);  for (i = 0; i < n; i++)   @{    double vi = gsl_vector_get(v, i);    printf("element = %d, value = %g, rank = %d\n",            i, vi, rank->data[i]);   @}  gsl_permutation_free (perm);  gsl_permutation_free (rank);@}@end example@node Sorting Examples@section ExamplesThe following example shows how to use the permutation @var{p} to printthe elements of the vector @var{v} in ascending order,@examplegsl_sort_vector_index (p, v);for (i = 0; i < v->size; i++)@{    double vpi = gsl_vector_get(v, p->data[i]);    printf("order = %d, value = %g\n", i, vpi);@}@end example@noindentThe next example uses the function @code{gsl_sort_smallest} to selectthe 5 smallest numbers from 100000 uniform random variates stored in anarray,@example#include <gsl/gsl_rng.h>#include <gsl/gsl_sort_double.h>intmain (void)@{  const gsl_rng_type * T;  gsl_rng * r;  int i, k = 5, N = 100000;  double * x = malloc (N * sizeof(double));  double * small = malloc (k * sizeof(double));  gsl_rng_env_setup();  T = gsl_rng_default;  r = gsl_rng_alloc (T);  for (i = 0; i < N; i++)    @{      x[i] = gsl_rng_uniform(r);    @}  gsl_sort_smallest (small, k, x, 1, N);  printf("%d smallest values from %d\n", k, N);  for (i = 0; i < k; i++)    @{      printf ("%d: %.18f\n", i, small[i]);    @}  return 0;@}@end exampleThe output lists the 5 smallest values, in ascending order,@example$ ./a.out 5 smallest values from 1000000: 0.0000054666306823491: 0.0000123844947665932: 0.0000175812747329473: 0.0000251310411840684: 0.000031369971111417@end example@node Sorting References and Further Reading@section References and Further Reading@noindentThe subject of sorting is covered extensively in Knuth's@cite{Sorting and Searching},@itemize @asis@itemDonald E. Knuth, @cite{The Art of Computer Programming: Sorting andSearching} (Vol 3, 3rd Ed, 1997), Addison-Wesley, ISBN 0201896850.@end itemize@noindentThe Heapsort algorithm is described in the following book,@itemize @asis@item Robert Sedgewick, @cite{Algorithms in C}, Addison-Wesley, ISBN 0201514257.@end itemize

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -