Advertisement
smatskevich

Sample sort

Mar 25th, 2017
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. using std::cin;
  5. using std::vector;
  6.  
  7. // Отрезок.
  8. struct CSegment {
  9.     int Left;
  10.     int Right;
  11.  
  12.     // Сравнение по правому краю. Если правые края равны, то по левому.
  13.     bool operator<( const CSegment& right ) const;
  14.     bool operator<=( const CSegment& right ) const;
  15.     bool operator>( const CSegment& right ) const;
  16.     bool operator>=( const CSegment& right ) const;
  17.  
  18.     CSegment() : Left( 0 ), Right( 0 ) {}
  19.     CSegment( int left, int right ) : Left( left ), Right( right ) {}
  20. };
  21.  
  22. bool CSegment::operator<( const CSegment& right ) const
  23. {
  24.     return ( Right < right.Right ) || ( Right == right.Right && Left < right.Left );
  25. }
  26.  
  27. bool CSegment::operator<=( const CSegment& right ) const
  28. {
  29.     return !( right < *this );
  30. }
  31. bool CSegment::operator>( const CSegment& right ) const
  32. {
  33.     return right < *this;
  34. }
  35. bool CSegment::operator>=( const CSegment& right ) const
  36. {
  37.     return !( *this < right );
  38. }
  39.  
  40. bool SegmentComparer( const CSegment& left, const CSegment& right )
  41. {
  42.     return left < right;
  43. }
  44.  
  45. // Функтор. Не используется.
  46. class CSegmentFunctor {
  47. public:
  48.     bool operator()( const CSegment& left, const CSegment& right ) { return left < right; }
  49. };
  50.  
  51. template<class T>
  52. inline void BubbleSort( std::vector<T>& arr, bool( *comparer )( const T&, const T& ) )
  53. {
  54.     const int n = arr.size();
  55.     for( int i = 0; i < n - 1; ++i ) {
  56.         bool swapped = false;
  57.         for( int j = 0; j < n - 1 - i; ++j ) {
  58.             if( comparer( arr[j + 1], arr[j] ) ) {
  59.                 std::swap( arr[j], arr[j + 1] );
  60.                 swapped = true;
  61.             }
  62.         }
  63.         if( !swapped ) {
  64.             break;
  65.         }
  66.     }
  67. }
  68.  
  69. int main()
  70. {
  71.     vector<CSegment> arr;
  72.     int left = 0;
  73.     int right = 0;
  74.     while( cin >> left >> right ) {
  75.         arr.push_back( CSegment( left, right ) );
  76.     }
  77.     BubbleSort( arr, SegmentComparer );
  78.     for( const CSegment& segment : arr ) {
  79.         std::cout << segment.Left << " " << segment.Right << std::endl;
  80.     }
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement