C++快速排序算法

From:

http://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F

Code:

#include "stdafx.h"
#include <functional>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;

template< typename BidirectionalIterator, typename Compare >
void quick_sort( BidirectionalIterator first, BidirectionalIterator last, Compare cmp ) {
	if( first != last ) {
		BidirectionalIterator left  = first;
		BidirectionalIterator right = last;
		BidirectionalIterator pivot = left++;

		while( left != right ) {
			if( cmp( *left, *pivot ) ) {
				++left;   //找出不符合条件的(大的)
			} else {
				while( (left != right) && cmp( *pivot, *right ) )
					--right; //找出不符合条件的(小的)
				std::iter_swap( left, right );  //交换
			}
		}

		--left;
		std::iter_swap( first, left );

		quick_sort( first, left, cmp );
		quick_sort( right, last, cmp );
	}
}

template< typename BidirectionalIterator >
inline void quick_sort( BidirectionalIterator first, BidirectionalIterator last ) {
	quick_sort( first, last,
		std::less_equal< typename std::iterator_traits< BidirectionalIterator >::value_type >()
		);
}

int _tmain(int argc, _TCHAR* argv[])
{
	int a[] = {4,9,8,3,6,5,1,7};
	int *s = a;
	int *e =a + sizeof(a)/sizeof(int) - 1;
	
	quick_sort(s,e);

	while(s <= e)
		cout<< *s++ <<" ";

	return 0;
}

Result:

posted @ 2014-08-05 20:01  anit_nait  阅读(183)  评论(0编辑  收藏  举报