sort


Sort a sequence.

Sort all elements in the range [ first ... last ) into ascending order. The first version uses operator< to compare elements, whereas the second version uses the binary function compare .

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class RandomAccessIterator >
void sort( RandomAccessIterator first, RandomAccessIterator last );

template< class RandomAccessIterator, class Compare >
void sort
  (
  RandomAccessIterator first,
  RandomAccessIterator last,
  Compare compare
  );
  

Complexity

Time complexity is O(N * log(N)). Space complexity is constant.

Example <ospace/osstd/examples/sort1.cpp>
#include <algorithm>

int array[ 6 ] = { 1, 50, -10, 11, 42, 19 };

void
main()
  {
  sort( array, array + 6 );

  for ( int i = 0; i < 6; ++i )
    cout << array[ i ] << ` `;
  cout << "\n";
  }

-10 1 11 19 42 50
Example <ospace/osstd/examples/sort2.cpp>
#include <algorithm>
#include <functional>
#include <iterator>

int array[] = { 1, 50, -10, 11, 42, 19 };

void
main()
  {
  int count = sizeof( array ) / sizeof( array[ 0 ] );
  ostream_iterator< int > iter( cout, " " );
  cout << "before: ";
  copy( array, array + count, iter );
  cout << "\nafter: ";

  sort( array, array + count, greater< int >() );

  copy( array, array + count, iter );
  cout << "\n";
  }

before: 1 50 -10 11 42 19
after: 50 42 19 11 1 -10

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.