sort.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef IGL_SORT_H
  2. #define IGL_SORT_H
  3. #include "igl_inline.h"
  4. #include <vector>
  5. #include <Eigen/Core>
  6. namespace igl
  7. {
  8. // Sort the elements of a matrix X along a given dimension like matlabs sort
  9. // function
  10. //
  11. // Templates:
  12. // DerivedX derived scalar type, e.g. MatrixXi or MatrixXd
  13. // DerivedIX derived integer type, e.g. MatrixXi
  14. // Inputs:
  15. // X m by n matrix whose entries are to be sorted
  16. // dim dimensional along which to sort:
  17. // 1 sort each column (matlab default)
  18. // 2 sort each row
  19. // ascending sort ascending (true, matlab default) or descending (false)
  20. // Outputs:
  21. // Y m by n matrix whose entries are sorted
  22. // IX m by n matrix of indices so that if dim = 1, then in matlab notation
  23. // for j = 1:n, Y(:,j) = X(I(:,j),j); end
  24. template <typename DerivedX, typename DerivedIX>
  25. IGL_INLINE void sort(
  26. const Eigen::PlainObjectBase<DerivedX>& X,
  27. const int dim,
  28. const bool ascending,
  29. Eigen::PlainObjectBase<DerivedX>& Y,
  30. Eigen::PlainObjectBase<DerivedIX>& IX);
  31. template <typename DerivedX, typename DerivedIX>
  32. // Only better if size(X,dim) is small
  33. IGL_INLINE void sort_new(
  34. const Eigen::PlainObjectBase<DerivedX>& X,
  35. const int dim,
  36. const bool ascending,
  37. Eigen::PlainObjectBase<DerivedX>& Y,
  38. Eigen::PlainObjectBase<DerivedIX>& IX);
  39. // Special case if size(X,dim) == 2
  40. template <typename DerivedX, typename DerivedIX>
  41. IGL_INLINE void sort2(
  42. const Eigen::PlainObjectBase<DerivedX>& X,
  43. const int dim,
  44. const bool ascending,
  45. Eigen::PlainObjectBase<DerivedX>& Y,
  46. Eigen::PlainObjectBase<DerivedIX>& IX);
  47. // Act like matlab's [Y,I] = SORT(X) for std library vectors
  48. // Templates:
  49. // T should be a class that implements the '<' comparator operator
  50. // Input:
  51. // unsorted unsorted vector
  52. // ascending sort ascending (true, matlab default) or descending (false)
  53. // Output:
  54. // sorted sorted vector, allowed to be same as unsorted
  55. // index_map an index map such that sorted[i] = unsorted[index_map[i]]
  56. template <class T>
  57. IGL_INLINE void sort(
  58. const std::vector<T> &unsorted,
  59. const bool ascending,
  60. std::vector<T> &sorted,
  61. std::vector<size_t> &index_map);
  62. }
  63. #ifdef IGL_HEADER_ONLY
  64. # include "sort.cpp"
  65. #endif
  66. #endif