Advertisement
Guest User

Untitled

a guest
Aug 26th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. bool IsSorted(int *firstElement, int arraySize);
  6. void Bogosort(int *firstElement, int arraySize);
  7. void RandomSorted(int *firstElement, int arraySize);
  8. void DisplayArray(int *firstElement, int arraySize, int index);
  9.  
  10. int main(int argc, const char * argv[])
  11. {
  12.     int const ARRAY_SIZE = 7;
  13.     int array[ARRAY_SIZE] = {21, 1, 423, 5, 22, 124, 2};
  14.    
  15.     srand(ARRAY_SIZE);
  16.  
  17.     Bogosort(array, ARRAY_SIZE);
  18.     DisplayArray(array, ARRAY_SIZE, 0);
  19.    
  20.     cout << endl;
  21.    
  22.     return 0;
  23. }
  24.  
  25. void DisplayArray(int *firstElement, int arraySize, int index)
  26. {
  27.     if(index >= arraySize) return;
  28.    
  29.     cout << firstElement[index] << " ";
  30.    
  31.     DisplayArray(firstElement, arraySize, ++index);
  32. }
  33.  
  34. bool IsSorted(int *firstElement, int arraySize)
  35. {
  36.     for(auto i = 0; i < arraySize - 1; ++i)
  37.     {
  38.         if(firstElement[i] > firstElement[i + 1])
  39.         {
  40.             return false;
  41.         }
  42.     }
  43.    
  44.     return true;
  45. }
  46.  
  47. void Bogosort(int *firstElement, int arraySize)
  48. {
  49.     while(!IsSorted(firstElement, arraySize))
  50.     {
  51.         RandomSorted(firstElement, arraySize);
  52.     }
  53. }
  54.  
  55. void RandomSorted(int *firstElement, int arraySize)
  56. {
  57.     auto n = arraySize;
  58.    
  59.     while(n > 1)
  60.     {
  61.         n--;
  62.         auto i = rand()%arraySize;
  63.         auto temp = firstElement[i];
  64.         firstElement[i] = firstElement[n];
  65.         firstElement[n] = temp;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement