Advertisement
smatskevich

BubbleSort

Oct 22nd, 2016
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using std::cin;
  4. using std::cout;
  5. using std::vector;
  6.  
  7. struct CPoint {
  8.     int X;
  9.     int Y;
  10.     CPoint( int x, int y ) : X( x ), Y( y ) {}
  11. };
  12.  
  13. // Вариант 1.
  14. // Оператор сравнения по удаленности точки от (0, 0).
  15. bool operator<( const CPoint& first, const CPoint& second )
  16. {
  17.     return first.X * first.X + first.Y * first.Y <
  18.         second.X * second.X + second.Y * second.Y;
  19. }
  20.  
  21. bool operator<=( const CPoint& first, const CPoint& second )
  22. {
  23.     return !( second < first );
  24. }
  25.  
  26. bool operator>( const CPoint& first, const CPoint& second )
  27. {
  28.     return second < first;
  29. }
  30.  
  31. bool operator>=( const CPoint& first, const CPoint& second )
  32. {
  33.     return !( first < second );
  34. }
  35.  
  36. // Вариант 2. Функция сравнения.
  37. bool CompareByDistanceFromZero( const CPoint& first, const CPoint& second )
  38. {
  39.     return first.X * first.X + first.Y * first.Y <
  40.         second.X * second.X + second.Y * second.Y;
  41. }
  42.  
  43. // Сортировка пузырьком.
  44. template<class T>
  45. void BubbleSort( vector<T>& arr, bool (* compareFunction)( const T&, const T& ) )
  46. {
  47.     int n = arr.size();
  48.     for( int i = n - 2; i >= 0; --i ) { // n - 1 итерация.
  49.         for( int j = 0; j <= i; ++j ) {
  50.             if( compareFunction( arr[j + 1], arr[j] ) ) {
  51.                 std::swap( arr[j], arr[j + 1] );
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57. int main()
  58. {
  59.     vector<CPoint> arr;
  60.     int x = 0;
  61.     int y = 0;
  62.     while( cin >> x >> y ) {
  63.         arr.push_back( CPoint( x, y ) );
  64.     }
  65.  
  66.     BubbleSort( arr, CompareByDistanceFromZero );
  67.  
  68.     for( int i = 0; i < static_cast<int>( arr.size() ); ++i ) {
  69.         cout << arr[i].X << ' ' << arr[i].Y << std::endl;
  70.     }
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement