fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. typedef pair<double*,int>(*TFunc)(double* a, int n);
  6.  
  7.  
  8. pair<double*,int> bubblesort(double* a, int n);
  9. pair<double*,int> vibor(double* a, int n);
  10. void sort(double* a, int n, TFunc f);
  11.  
  12. ostream& operator<< (ostream& os, const pair<double*,int>& p)
  13. {
  14. for(int i = 0; i < p.second; ++i)
  15. os << p.first[i] << "\t";
  16. return os << endl;
  17. }
  18.  
  19. TFunc menu();
  20.  
  21. int main()
  22. {
  23. TFunc item;
  24. int n;
  25. cout << "Enter the amount of elements in array --> " << endl;
  26. cin >> n;
  27. double* a = new double[n];
  28. cout << "Array before selecting a way to sort:\n";
  29. for (int i = 0; i < n; i++)
  30. {
  31. cout << i + 1 << "-ый элемент: ";
  32. cin >> a[i];
  33. }
  34. for (int i = 0; i < n; i++)
  35. {
  36. cout << a[i] << " ";
  37. }
  38. cout << endl;
  39.  
  40. item = menu();
  41. if (item == NULL)
  42. {
  43. cout << "Function number is entered incorrectly!";
  44. }
  45. else
  46. {
  47. sort(a, n, item);
  48. }
  49. delete[] a;
  50. }
  51.  
  52. pair<double*,int> bubblesort(double* a, int n)
  53. {
  54. for (int i = 0; i < n; i++)
  55. {
  56. for (int j = 0; j < n - 1; j++)
  57. {
  58. if (a[j] < a[j + 1])
  59. {
  60. double temp = a[j];
  61. a[j] = a[j + 1];
  62. a[j + 1] = temp;
  63. }
  64. }
  65. }
  66. return make_pair(a,n);
  67. }
  68.  
  69. pair<double*,int> vibor(double* a, int n)
  70. {
  71. for (int i = 0; i < n - 1; i++)
  72. {
  73. int biggestIndex = i;
  74. for (int j = i + 1; j < n; j++)
  75. {
  76. if (a[j] > a[biggestIndex])
  77. {
  78. biggestIndex = j;
  79. }
  80. }
  81. swap(a[i], a[biggestIndex]);
  82. }
  83. return make_pair(a,n);
  84. }
  85.  
  86. void sort(double* a, int n, TFunc f)
  87. {
  88. cout << f(a, n);
  89. }
  90.  
  91. TFunc menu()
  92. {
  93. TFunc fun_items[] = { bubblesort, vibor };
  94. int key;
  95. cout << "Selecting a way to sort array:\n"
  96. "1 - bubblesort, 2 - vibor\n";
  97. cin >> key;
  98. switch (key)
  99. {
  100. case 1:;
  101. case 2: return fun_items[key - 1];
  102. default: return NULL;
  103. }
  104. }
  105.  
Success #stdin #stdout 0.01s 5516KB
stdin
7
2 8 3 7 4 0 9
1

stdout
Enter the amount of elements in array --> 
Array before selecting a way to sort:
1-ый элемент: 2-ый элемент: 3-ый элемент: 4-ый элемент: 5-ый элемент: 6-ый элемент: 7-ый элемент: 2 8 3 7 4 0 9 
Selecting a way to sort array:
1 - bubblesort, 2 - vibor
9	8	7	4	3	2	0