// ***************************************************************************** // ***************************************************************************** // * // platform : Fedora 16 x86_64 * // compiler : gcc-c++-4.6.2-1.fc16.x86_64 * // * // test 1 : g++ main.cpp && ./a.out * // test 2 : g++ -O2 main.cpp && ./a.out * // test 3 : g++ -O3 main.cpp && ./a.out * // * // original data : {12, -1, 2} to be sorted into : {-1, 2, 12} * // * // ***************************************************************************** // ***************************************************************************** #include // for uint32_t #include // for std::size_t and std::ptrdiff_t #include // for standard output #include // for EXIT_SUCCESS and EXIT_FAILURE // ***************************************************************************** // swap values pointed by x and y * // ***************************************************************************** template void swap(T *const x, T *const y) { if (*x!=*y) { const T tmp = *y; *y = *x; *x = tmp; }; } // --------------------------------------------------------------------------- // specialisation for T = float // --------------------------------------------------------------------------- template<> inline void swap(float *const x, float *const y) { swap(reinterpret_cast(x),reinterpret_cast(y)); } // ***************************************************************************** // quicksort (with pointers) * // --------------------------------------------------------------------------- * // data are sorted in the range [ptr_start ; ptr_end[ * // ***************************************************************************** template void quicksort(T *const ptr_start, const T *const ptr_end) { const std::ptrdiff_t n = ptr_end-ptr_start; if (n>=2) { if (n==2) { if (*ptr_start>*(ptr_start+1)) { swap(ptr_start,ptr_start+1); }; } else { swap(ptr_start,ptr_start+(n>>1)); // std::cout<<*ptr_start<ptr_start)&&(*ptr_right>pivot)) { ptr_right--; }; if (ptr_left(ptr_left++,ptr_right--); } }; if ((ptr_right==ptr_left)&&(*ptr_right>pivot)) { ptr_right--; }; swap(ptr_start,ptr_right); quicksort(ptr_start,ptr_right); quicksort(++ptr_right,ptr_end); }; }; } // ***************************************************************************** // main routine * // ***************************************************************************** int main(void) { typedef float T; const std::size_t N = 3; T tab[N] = {12, -1, 2}; std::cout<<"\noriginal data ( {12, -1, 2} )\n\n"; for (std::size_t i=0;i(tab,tab+N); std::cout<<"sorted data ( shoud be {-1, 2, 12} )\n\n"; for (std::size_t i=0;i