oaktree

Quick Sort (Optimized + Insertion Sort) - C++

Mar 24th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <cstdlib>
  5. #include <iterator>
  6. #include <algorithm>
  7.  
  8. using namespace std;
  9. void swap(vector<char>::iterator a, vector<char>::iterator b) {
  10.     char tmp = *a;
  11.     *a = *b;
  12.     *b = tmp;
  13. }
  14. bool sorted(vector<char>::iterator begin, vector<char>::iterator end) {
  15.     for (auto i = begin; i != end - 1; i++) {
  16.         if (*(i + 1) < *i) return false;
  17.     }
  18.  
  19.     return true;
  20. }
  21. void insertionsort(vector<char>::iterator begin, vector<char>::iterator end) {
  22.  
  23.     while (!sorted(begin, end)) {
  24.         for (auto i = begin + 1; i != end; i++) {
  25.  
  26.             if (*(i - 1) > *i) {
  27.                 char hold = *i;
  28.                 auto pos = i;
  29.  
  30.                 while (pos > begin && *(pos - 1) > hold) {
  31.                    
  32.                     *pos = *(pos - 1);
  33.                     pos--;
  34.                 }
  35.  
  36.                 *pos = hold;
  37.             }
  38.         }
  39.     }
  40. }
  41. void quicksort(vector<char>::iterator begin, vector<char>::iterator end) {
  42.     /*
  43.      * Recursion Terminating Conditions:
  44.     */
  45.     if (distance(begin,end) <= 1) return;
  46.     if (distance(begin, end) <= 10) {
  47.         insertionsort(begin, end);
  48.         return;
  49.     }
  50.  
  51.     vector<char>::iterator a, b;
  52.  
  53.     char pivot = *(end - 1);
  54.  
  55.     a = begin; b = end - 1;
  56.  
  57.     while(b > a) {
  58.         if ( *(b-1) > pivot) {
  59.             *b = *(b-1);
  60.             b--;
  61.         } else {
  62.             swap(b-1, a);
  63.             a++;
  64.         }
  65.     }
  66.  
  67.     *b = pivot;
  68.  
  69.     quicksort(begin, b);
  70.     quicksort(b + 1, end);
  71. }
  72.  
  73.  
  74. int main() {
  75.  
  76.     cout << "give me a string" << endl;
  77.     string s; getline(cin, s);
  78.  
  79.     vector<char> vec(s.begin(), s.end());
  80.  
  81.     quicksort(vec.begin(), vec.end());
  82.  
  83.     string str(vec.begin(), vec.end());
  84.  
  85.     cout << str << endl;
  86.  
  87.     return 0;
  88. }
Add Comment
Please, Sign In to add comment