调试得有点蛋疼……都知道原理,就附上代码咯……
quick_sort.h
1 #ifndef QUICK_SORT_H 2 #define QUICK_SORT_H 3 #include4 #include 5 using namespace std; 6 class quick_sort 7 { 8 public: 9 quick_sort();10 void sort(int start, int end);11 void partition(int start, int end);12 void output();13 int get_size();14 private:15 vector vct;16 void _swep(int pos1, int pos2);17 };18 19 #endif // QUICK_SORT_H
quick_sort.cpp
1 #include "quick_sort.h" 2 #include3 #include 4 #include 5 6 quick_sort::quick_sort() 7 { 8 srand((unsigned)time(NULL)); 9 for (int loop_var = 0; loop_var != 10; loop_var++) {10 vct.push_back(rand() %100);11 }12 }13 void quick_sort::sort(int start, int end)14 {15 if (start > end || end > vct.size()) {16 return;17 }18 if (start == end) {19 return ;20 }21 int rand_pos = rand()%(end - start)+start; //get the random postion22 cout << "postion:" << rand_pos << endl;23 this->_swep(start, rand_pos); //move to first place24 int last = start;25 for (int loop_var = start; loop_var <= end; loop_var++) { //patition26 if (vct[loop_var] < vct[start]) {27 last++;28 this->_swep(loop_var, last);29 }30 }31 this->_swep(start, last); //move to the current place32 sort(start, last);33 sort(++last, end);34 }35 36 void quick_sort::output()37 {38 for (vector ::iterator iter = vct.begin(); iter != vct.end(); iter++) {39 cout << *iter << " ";40 }41 cout << endl;42 }43 int quick_sort::get_size()44 {45 return vct.size();46 }47 48 void quick_sort::_swep(int pos1, int pos2)49 {50 if(pos1 >= vct.size() || pos2 >= vct.size()) {51 throw runtime_error("the postion is not true!\n");52 }53 int temp = vct[pos1];54 vct[pos1] = vct[pos2];55 vct[pos2] = temp;56 }
1 #include2 #include 3 #include "quick_sort.h" 4 using namespace std; 5 6 int main(int argc, char *argv[]) 7 { 8 quick_sort qs; 9 qs.output();10 qs.sort(0, qs.get_size()-1);11 qs.output();12 }
posted on 2012-06-15 22:15 阅读( ...) 评论( ...)