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
|
#include <algorithm>
#include <iostream>
template <typename Iterator, class Compare>
int part( Iterator begin, Iterator end, Compare cmp)
{
if( end - begin < 2 ) return end-begin;
Iterator pivot = begin;
Iterator left = begin + 1;
Iterator right = end - 1;
while( left < right )
{
while( left < end-1 && cmp(*left,*pivot) )
{
++ left;
std::cerr << "L" <<left-pivot; // DEBUG
}
while( right > begin && cmp(*pivot,*right) )
{
-- right;
std::cerr << "R" <<right-pivot; // DEBUG
}
// DEBUG
std::cout << "|left:"<< (int)(left-begin)
<< ",right:"<<(int)(right-begin)
<< "of"<< end-begin << " ";
if( left < right ) std::swap(*left,*right);
std::cerr << " PART|" << begin << "| "; // DEBUG
}
std::cerr << "MARK_0\n";
// DEBUG
std::cerr << "right:"<<(int)(right-begin)
<< " pivot:"<<(int)(pivot-begin) << '\n';
std::swap( *right, *pivot ); // Here I get a segfault, why?
std::cerr << "MARK_1\n"; //DEBUG
return right - begin;
}
template <typename Iterator, class Compare>
void quicksort( Iterator begin, Iterator end, Compare cmp )
{
if( end - begin < 2 ) return;
int pivot = part( begin, end, cmp );
quicksort( begin, begin + pivot, cmp );
quicksort( begin + pivot + 1, end, cmp );
}
#include <string>
int main()
{
char * test_0 = (char*)"zyx";/*wvutsrqponmlkjihgfedcba";*/
char * test_1 = (char*)"a";
char * test_2 = (char*)"";
char * test = test_0;
int size = 0; while( test[size] != '\0') ++size;
std::cout << test << '\n';
std::cout << part(test,test+size,[](char a, char b){ return a < b;} ) << '\n';
std::cout << test << '\n';
quicksort( test,test+size,[](char a, char b){return a < b;} );
std::cout << test << '\n';
}
| |