C++模板实现,快速排序

   可以排序。(发现性能更好的再调整)

测试:

template
bool quickSort( std::vector& datas, const C& comparator );
bool lessThan( int i, int j )
{
    return  i <=j;
}

void test( )
{
	std::vector vTests;

	srand( time(NULL) );
	for( int i = 0; i < 10; ++i )
	{
		vTests.push_back( rand( ) );
	}

	quickSort( vTests, lessThan );
}

实现:

template
typename std::vector::size_type findFisrtElemPos( 
            std::vector& datas, const C& comparator,
            typename std::vector::size_type startPos, 
            typename std::vector::size_type finalPos )
{
    const T elem = datas.at(startPos);
    bool  hasChanged = false;
    while( startPos < finalPos )
    {
        while( startPos < finalPos && comparator( elem,datas.at(finalPos) ) )
        {
            --finalPos;
        }
        if( startPos == finalPos )
        {
            break;
        }
        hasChanged = true;
        datas[startPos] = datas.at(finalPos);
        
        while( startPos < finalPos && comparator( datas.at( startPos ), elem ) )
        {
            ++startPos;
        }
        if( startPos == finalPos )
        {
            break;
        }
        datas[finalPos] = datas.at(startPos);
    }
    if( hasChanged )
    {
        datas[startPos] = elem;
    }
    
    return startPos;
}

template
bool quickSortImp( std::vector& datas, const C& comparator,
                   typename std::vector::size_type startPos, 
                   typename std::vector::size_type finalPos )
{
    if( startPos >=  finalPos )
    {
        return false;
    }
    std::vector::size_type midPos = 
            findFisrtElemPos( datas, comparator, startPos, finalPos );
    if( midPos != startPos )
    {
        quickSortImp( datas, comparator, startPos, midPos-1 );
        quickSortImp( datas, comparator, midPos + 1, finalPos );
    }
    
    return true;
}


template
bool quickSort( std::vector& datas, const C& comparator )
{
    return quickSortImp( datas, comparator, 0, datas.size( )-1 );
}

 

你可能感兴趣的:(c++)