Advertisement
Okorosso

bucketSort

Mar 17th, 2021
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. std::vector<std::string> bucketSort(std::vector<std::string> &arr) {
  6.     using namespace std;
  7.     vector<vector<string>> bucket(74); // because I use table from 48 - 122 indices,
  8.     // that's equal from letter 1 to letter z in lower case in ascii table
  9.     vector<string> answer;
  10.  
  11.     for (auto elem : arr) {
  12.         int index = ((int) elem[0]) - 48; // minus 48 because I use table from 48 to 122
  13.         // that's equal '1' to 'z' in ascii
  14.         bucket[index].push_back(elem);
  15.     }
  16.  
  17.     for (int i = 0; i < bucket.size(); i++) {
  18.         sort(bucket[i].begin(), bucket[i].end()); // sort our separated by first letter strings
  19.     }
  20.  
  21.     for (int i = 0; i < bucket.size(); i++) { // add our sorted subarrs in one big
  22.         if (!bucket[i].empty()) {
  23.             for (int j = 0; j < bucket[i].size(); j++) {
  24.                 answer.push_back(bucket[i][j]);
  25.             }
  26.         }
  27.     }
  28.     return answer;
  29. }
  30.  
  31. int main() {
  32.     using namespace std;
  33.     ifstream in("input.txt");
  34.     ofstream out("output.txt");
  35.     int count;
  36.     in >> count;
  37.     vector<string> toSort(count);
  38.  
  39.     for (int i = 0; i < count; i++){
  40.         in >> toSort[i];
  41.     }
  42.  
  43.     vector<string> answ = bucketSort(toSort);
  44.     for (auto elem:answ) {
  45.         out << elem << '\n';
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement