Advertisement
daniil_mironoff

Untitled

Nov 25th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3.  
  4. using namespace std;
  5.  
  6. // Выводит массив
  7. void printArr(int* arr, unsigned int size) {
  8.     for (int i = 0; size > i; i++) {
  9.         cout << arr[i] << ' ';
  10.     }
  11.  
  12.     cout << endl;
  13. }
  14.  
  15. // Меняет значения у аргументов(!) местами
  16. void swap(int &x, int &y) {
  17.     int tempInt = x;
  18.     x = y;
  19.     y = tempInt;
  20. }
  21.  
  22. // Проверяет на корректность массив
  23. bool correct(int *arr, int size) {
  24.     // Цикл, сравнивающий элементы
  25.     for (int i = 1; size > i; i++) {
  26.         if (arr[i] < arr[i - 1]) {
  27.             return 0;
  28.         }
  29.     }
  30.  
  31.     return 1;
  32. }
  33.  
  34. // Меняет первый элемента массива с случайным size раз (Перемешивание)
  35. void shuffle(int *arr, int size) {
  36.     for (int i = 0; i < size; ++i) {
  37.         swap(arr[i], arr[(rand() % size)]);
  38.     }
  39. }
  40.  
  41. // Сортирует, пока массив не будет отсортирован)
  42. void bogoSort(int *arr, int size) {
  43.     while (!correct(arr, size)) {
  44.         shuffle(arr, size);
  45.         printArr(arr, size);
  46.     }
  47. }
  48.  
  49. int main() {
  50.     srand(time(NULL));
  51.     int arr[5] = { 0, 5, 2, 3, 1 };
  52.     printArr(arr, 5);
  53.  
  54.     bogoSort(arr, 5);
  55.    
  56.    
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement