zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    为什么说 Java 程序员必须掌握 Spring Boot ?(转)
    Vert.x 之 HelloWorld
    Vert.x Web 文档手册
    Vert.x Core 文档手册
    Android数据存储五种方式总结
    设置简单的定时
    自定义dialog
    Android DrawerLayout 高仿QQ5.2双向侧滑菜单
    Fragments碎片
    理解Fragment生命周期
  • 原文地址:https://www.cnblogs.com/anit/p/3893064.html
Copyright © 2011-2022 走看看