快速选择算法 C++实现

快速选择算法

今天早上想起来了,然后就学了一下,然后发现……这特喵不就是快排删了一半么,总的来说算法本身挺简单的,就是时间复杂度不太好预期(感觉实用性真的不高啊,这个算法)
不过还是写了一下。
不支持C++的语法高亮难受

template< class RandomIt >
inline RandomIt _find_nth_smaller_element(RandomIt * _first,RandomIt * _last,size_t nth)
{
    RandomIt * first = _first;
    RandomIt * last = _last - 1;
    auto key = *first;
    while(first != last)
    {
        while(first != last && key < *last)
            last--;
        *first = *last;
        while(first != last && !(key < *first))
            first++;
        *last = *first;
    }
        *first = key; 
        //快排partition过程

    if(first - _first == nth - 1)
        return key;
    else if(first - _first > nth - 1)
        return _find_nth_smaller_element(_first , first, nth);
    else
        return _find_nth_smaller_element(first + 1 , _last , nth - (first - _first) - 1);
        //然后选取元素所在的区间进行快排就行了
}

你可能感兴趣的:(算法实现)