Loading...
Searching...
No Matches
msg_sort_with_permutation.h
Go to the documentation of this file.
#ifndef _RHEOLEF_MSG_SORT_WITH_PERMUTATION_H
#define _RHEOLEF_MSG_SORT_WITH_PERMUTATION_H
/*
sort_with_permutation - Computes the permutation of values that gives
a sorted sequence.
Input Parameters:
v - values to sort. Unchanged
p - permutation array. Must be initialized to 0:n-1 on input.
n - number of values to sort
Notes:
inspirated from petsc-2.0.22/sortip.c
with a bug fix in quicksort as in http://iulib.googlecode.com/hg/colib/quicksort.h
*/
#include "rheolef/compiler.h"
namespace rheolef {
template<class RandomIterator, class SizeRandomIterator, class Size>
void
quick_sort_with_permutation(
RandomIterator v,
SizeRandomIterator p,
Size start,
Size end)
{
if (start + 1 >= end) return;
typedef typename std::iterator_traits<RandomIterator>::value_type T;
const T& pivot = v[p[(start+end-1)/2]];
Size lo = start, hi = end;
for(;;) {
while (lo < hi && v[p[lo]] < pivot) lo++;
while (lo < hi && v[p[hi-1]] >= pivot) hi--;
if (lo == hi || lo+1 == hi) break;
std::swap (p[lo], p[hi-1]);
lo++; hi--;
}
Size split1 = lo;
hi = end;
for(;;) {
while (lo < hi && v[p[lo]] == pivot) lo++;
while (lo < hi && v[p[hi-1]] > pivot) hi--;
if (lo == hi || lo+1 == hi) break;
std::swap (p[lo], p[hi-1]);
lo++; hi--;
}
Size split2 = lo;
quick_sort_with_permutation (v, p, start, split1);
quick_sort_with_permutation (v, p, split2, end);
}
template<class RandomIterator, class SizeRandomIterator, class Size>
void
bubble_sort_with_permutation(
RandomIterator v,
SizeRandomIterator p,
Size n)
{
for (Size k = 0; k < n; k++) {
Size vk = v [p [k]];
for (Size j = k+1; j < n; j++) {
if (vk > v [p [j]]) {
std::swap (p[k], p[j]);
vk = v [p [k]];
}
}
}
}
template<class RandomIterator, class SizeRandomIterator, class Size>
void
sort_with_permutation(
RandomIterator v,
SizeRandomIterator p,
Size n)
{
const Size n_qsort_min = 8;
if (n >= n_qsort_min) {
quick_sort_with_permutation (v, p, Size(0), n);
} else {
bubble_sort_with_permutation (v, p, n);
}
}
} // namespace rheolef
#endif // _RHEOLEF_MSG_SORT_WITH_PERMUTATION_H
T
Expr1::float_type T
Definition field_expr.h:230
rheolef
This file is part of Rheolef.
Definition compiler_eigen.h:39
rheolef::sort_with_permutation
void sort_with_permutation(RandomIterator v, SizeRandomIterator p, Size n)
Definition msg_sort_with_permutation.h:91
rheolef::quick_sort_with_permutation
void quick_sort_with_permutation(RandomIterator v, SizeRandomIterator p, Size start, Size end)
Definition msg_sort_with_permutation.h:42
rheolef::bubble_sort_with_permutation
void bubble_sort_with_permutation(RandomIterator v, SizeRandomIterator p, Size n)
Definition msg_sort_with_permutation.h:74
p
Definition sphere.icc:25