SHARE
TWEET

Selection Sort - C++

oaktree Mar 19th, 2016 (edited) 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. void selectionsort(vector<char>& vec) {
  9.     int n = vec.size();
  10.    
  11.     // start from first element till last
  12.     for (int i = 0; i < n; i++) {
  13.  
  14.         int min_pos = i; // assume first element is the smallest
  15.  
  16.         for (int j = i + 1; j < n; j++) {
  17.             // update position of min element if we find a smaller one
  18.             if (vec[j] < vec[min_pos]) {
  19.                 min_pos = j;
  20.             }
  21.         }
  22.  
  23.         // if the minimun is not at position i, we must swap
  24.         if (min_pos != i) {
  25.             int tmp = vec[i];
  26.             vec[i] = vec[min_pos];
  27.             vec[min_pos] = tmp;
  28.         }
  29.     }
  30. }
  31.  
  32. int main() {
  33.     cout << "give me a string" << endl;
  34.     string s; getline(cin, s);
  35.  
  36.     vector<char> vec(s.begin(), s.end());
  37.  
  38.     if (!vec.empty()) selectionsort(vec);
  39.  
  40.     string str(vec.begin(), vec.end());
  41.  
  42.     cout << str << endl;
  43.     return 0;
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top