码迷,mamicode.com
首页 > 编程语言 > 详细

C++快速排序算法

时间:2014-08-05 22:12:50      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   2014   

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:

bubuko.com,布布扣

C++快速排序算法,布布扣,bubuko.com

C++快速排序算法

标签:style   blog   http   color   os   io   strong   2014   

原文地址:http://www.cnblogs.com/anit/p/3893064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!