Advertisement
oaktree

Bogo Sort - C++

Mar 12th, 2016
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. bool is_sorted(const vector<char>& vec) {
  9.    
  10.     for (int i = 1, n = vec.size(); i < n; i++) {
  11.         if (vec[i-1] > vec[i]) return false;
  12.         // returns false if an element is smaller than one to its left
  13.     }
  14.  
  15.     return true;
  16. }
  17.  
  18. void shuffle(vector<char>& vec) {
  19.     int i,n, tmp, rand_idx;
  20.  
  21.     for(i = 0, n = vec.size(); i < n; i++) {
  22.        
  23.         tmp = vec[i]; // store temporarily
  24.        
  25.         rand_idx = rand() % n; // pick a random index in the vector/array
  26.  
  27.         // swap each element in vector/array with another one that is chosen randomly
  28.         vec[i] = vec[rand_idx];
  29.         vec[rand_idx] = tmp;
  30.     }
  31. }
  32.  
  33. void bogosort(vector<char>& vec) {
  34.     while( !is_sorted(vec) ) shuffle(vec);
  35. }
  36.  
  37. int main() {
  38.     cout << "give me a string" << endl;
  39.     string s; getline(cin, s);
  40.  
  41.     vector<char> vec(s.begin(), s.end());
  42.  
  43.     if (!vec.empty()) bogosort(vec);
  44.  
  45.     string str(vec.begin(), vec.end());
  46.  
  47.     cout << str << endl;
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement