說在前面的廢話
話說快一年沒寫過部落格了。。。
在建站之前就先用csdn寫吧
這次要說的東西也沒有啥,主要是想寫一次快排(學了這麼就快排都沒寫過你敢信
用法類似於stl裡面的sort,有兩個版本。
不知道為什麼寫了很長時間。。。這麼短的代碼
還是感覺數組版的好寫一點
學過快排的同學可以不用看下面這段了 快排的基本思想
1.選取一個基準
2.將比它”小”的放在它前面,比他“大”的放在後面(廣義的小和大)
3.遞迴處理前面那一段和後面那一段 實現步驟
函數傳入的是指向第一個元素的迭代器( begin begin)和指向最後一個元素後一個的迭代器( end end)
還可以傳入一個比較函數( comp comp)
考慮快排的操作: 1.選定一個基準
我們選擇第一個元素的值作為排序的基準,把它的迭代器記作 temp
然後記錄一前一後兩個迭代器,記作front和back。 2.整理
每一輪,我們用back迭代器從後向前遍曆,直到當前元素的值小於temp指向元素的值,然後交換他們的值,並讓temp指向現在的位置再使back向前移動一次;隨後對front迭代器進行類似的操作。
持續進行上面的操作,直到front和back間沒有元素,即所有元素都被遍曆過。 3.遞迴處理
temp所在的元素已經是其應該在的位置,所以只需要處理begin~temp 和 temp+1~end這兩個區間的 代碼
#include <iostream>#include <vector>using namespace std;template <typename _T>void _swap(_T& _a, _T& _b){ _T temp = _b; _b = _a; _a = temp;}template <typename _Random_Access_Iterator>void my_quick_sort(_Random_Access_Iterator _begin, _Random_Access_Iterator _end){ if (_end - _begin <= 1) return; _Random_Access_Iterator _temp = _begin; _Random_Access_Iterator _front = _begin; _Random_Access_Iterator _back = _end - 1; while (true) { while (_back - _front >= 0) { if (*_back < *_temp) { _swap(*_back, *_temp); _temp = _back; _back--; break; } _back--; } while (_back - _front >= 0) { if (*_temp < *_front) { _swap(*_temp, *_front); _temp = _front; _front++; break; } _front++; } if (_back - _front < 0) break; } my_quick_sort(_begin, _temp); my_quick_sort(_temp + 1, _end);}template <typename _Random_Access_Iterator, typename _Compare>void my_quick_sort(_Random_Access_Iterator _begin, _Random_Access_Iterator _end, _Compare _comp){ if (_end - _begin <= 1) return; _Random_Access_Iterator _temp = _begin; _Random_Access_Iterator _front = _begin; _Random_Access_Iterator _back = _end - 1; while (true) { while (_back - _front >= 0) { if (_comp(*_back, *_temp)) { _swap(*_back, *_temp); _temp = _back; _back--; break; } _back--; } while (_back - _front >= 0) { if (_comp(*_temp, *_front)) { _swap(*_temp, *_front); _temp = _front; _front++; break; } _front++; } if (_back - _front < 0) break; } my_quick_sort(_begin, _temp, _comp); my_quick_sort(_temp + 1, _end, _comp);}template<typename _T>bool compare(const _T& a, const _T& b){ return a > b;}int main(int argc, char** argv){ vector<int> a={95,1,4,2,6,9,3,6562,324,54,32243,123,43,657457,100,43}; my_quick_sort(a.begin (), a.end (), compare<int>); for (auto i : a) { cout << i << endl; } size_t t; cin >> a[1]; return 0;}