fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <math.h>
  5.  
  6. using namespace std;
  7.  
  8. // to use user-defined comparison for sorting,
  9. // the user needs to provide a function that
  10. // returns true when the left argument should
  11. // go earlier than the right argument (so for
  12. // increasing order the comparison function
  13. // returns true if i<j);
  14. // this function ensures 3 rules
  15. // 1. even numbers precede odd numbers
  16. // 2. odd numbers should decrease
  17. // 3. even numbers should increase
  18.  
  19. bool is_less(int i, int j)
  20. {
  21. // even numbers go before odd numbers
  22.  
  23. if ((i%2==0) && (j%2==1))
  24. return true;
  25.  
  26. // even numbers should increase
  27.  
  28. if ((i%2==0) && (j%2==0))
  29. return (i<j);
  30.  
  31. // odd numbers should decrease
  32.  
  33. if ((i%2==1) && (j%2==1))
  34. return (i>j);
  35.  
  36. // otherwise, i should not be forced to
  37. // precede j
  38.  
  39. return false;
  40. }
  41.  
  42. int main()
  43. {
  44. int i;
  45. int n = 18;
  46.  
  47. // initialize random number generator with random seed 123
  48.  
  49. srand48(123);
  50.  
  51. // two vectors of n elements of type int
  52.  
  53. vector<int> v(n);
  54.  
  55. // generate both vectors random, each variable from
  56. // uniform distribution over interval {0, ..., 99}
  57.  
  58. for (i=0; i<n; i++)
  59. v[i] = drand48()*100;
  60.  
  61. // print out the vector
  62.  
  63. cout << "initial vector:" << endl;
  64. for (i=0; i<n; i++)
  65. cout << " " << v[i] << endl;
  66.  
  67. // sort the vector (ascending order)
  68. // (v.begin() and v.end() indicate that the sorting
  69. // should consider the entire vector from its start
  70. // on the left until the end on the right)
  71.  
  72. sort( v.begin(), v.end(), is_less);
  73.  
  74. // print out the vector
  75.  
  76. cout << "sorted vector:" << endl;
  77. for (i=0; i<n; i++)
  78. cout << " " << v[i] << endl;
  79.  
  80. // return from main with 0
  81.  
  82. return 0;
  83. }
  84.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
initial vector:
   27
   41
   92
   12
   12
   34
   62
   83
   69
   15
   78
   36
   93
   14
   85
   11
   81
   39
sorted vector:
   12
   12
   14
   34
   36
   62
   78
   92
   93
   85
   83
   81
   69
   41
   39
   27
   15
   11