partial_sort_copy |
Sort the smallest n elements of a sequence and copy the result.
Sort the first n
elements of [ first ... last
) where n = min ((
last - first ), (
result_last - result_first
)) and place the result into [ result_first...result_first
+ n ). Return the smaller
of result_last or result_first
+ n , where n
= last -
first . The first version sorts the elements
using operator< , whereas the second version
uses the binary function compare .
#include <algorithm>
template< class InputIterator, class RandomAccessIterator >
RandomAccessIterator partial_sort_copy
(
InputIterator first,
InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last
);
template
<
class InputIterator,
class RandomAccessIterator,
class Compare
>
RandomAccessIterator partial_sort_copy
(
InputIterator first,
InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last,
Compare compare
);
Time complexity is (
last - first )
* log ( n ). Space complexity is constant.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
int numbers[ 6 ] = { 5, 2, 4, 3, 1, 6 };
void
main()
{
int result[ 3 ];
partial_sort_copy
(
numbers,
numbers + 6,
result,
result + 3
);
for ( int i = 0; i < 3; ++i )
cout << result[ i ] << ` `;
cout << "\n";
}
1 2 3
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <iterator>
#include <vector>
void
main()
{
vector< int > v1( 10 );
for ( int i = 0; i < v1.size(); ++i )
v1[ i ] = rand() % 10;
vector< int > result ( 5 );
ostream_iterator< int > iter( cout, " " );
copy( v1.begin(), v1.end(), iter );
cout << "\n";
partial_sort_copy( v1.begin(), v1.end(), result.begin(), result.end() );
copy( result.begin(), result.end(), iter );
cout << "\n";
}
6 0 2 0 6 7 5 5 8 6
0 0 2 5 5
#include <iostream>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <vector>
char* names[] = { "aa", "ff", "dd", "ee", "cc", "bb" };
bool
str_compare( const char* a_, const char* b_ )
{
return ::strcmp( a_, b_ ) < 0 ? 1 : 0;
}
void
main()
{
const unsigned nameSize = sizeof( names ) / sizeof( names[ 0 ] );
vector< char* > v1( nameSize );
for ( int i = 0; i < v1.size(); ++i )
v1[ i ] = names[ i ];
ostream_iterator< char* > iter( cout, " " );
copy( v1.begin(), v1.end(), iter );
cout << "\n";
vector< char* > result ( 5 );
partial_sort_copy
(
v1.begin(),
v1.end(),
result.begin(),
result.end(),
str_compare
);
copy( v1.begin(), v1.end(), iter );
cout << "\n";
}
aa ff dd ee cc bb
aa ff dd ee cc bb
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.