1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
// view of an array with the element positions offset by BASE
template < typename T, std::size_t BASE = 1 > struct array_view {
std::size_t size() const { return sz ; }
T& operator[] ( std::size_t pos ) { return ptr[ pos - BASE ] ; } // invariant pos < ( size() + BASE )
// const T& operator[] ( std::size_t pos ) const { return ptr[ pos - BASE ] ; }
T* ptr ;
std::size_t sz ;
};
template < typename T > array_view<T,1> make_one_based( T* ptr, std::size_t n ) { return { ptr, n } ; }
template < typename T, std::size_t N > array_view<T,1> make_one_based( T (&arr)[N] ) { return { arr, N } ; }
void hpsort( /*long n, double ra[] */ array_view<double,1> ra ) { // *** modifioed
const long n = ra.size() ; // *** added
// *** rest of the function is retained verbatim
// Sorts an array ra[1..n] into ascending numerical order using the Heapsort algorithm. n is
// input; ra is replaced on output by its sorted rearrangement.
unsigned long i,ir,j,l;
double rra;
if (n < 2) return;
l = (n >> 1)+1;
ir = n;
for (;;) {
if (l > 1) {
rra = ra[--l];
} else {
rra = ra[ir];
ra[ir] = ra[1];
if (--ir == 1) {
ra[1] = rra;
break;
}
}
i = l;
j = l+l;
while (j <= ir) {
if (j < ir && ra[j] < ra[j+1]) j++;
if (rra < ra[j]) {
ra[i] = ra[j];
i = j;
j <<= 1;
} else break;
}
ra[i] = rra;
}
}
int main()
{
double a[] = { 34, 43, 98, 56, 57, 68, 97, 14, 98, 74, 64, 63, 55, 35, 24, 25, 45, 67 } ;
for( double v : a ) std::cout << v << ' ' ;
std::cout << '\n' ;
auto array_view = make_one_based(a) ;
hpsort( array_view ) ;
for( double v : a ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
|