Advertisement
Guest User

Untitled

a guest
Mar 26th, 2015
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <algorithm>
  5. using std::cout;
  6. using std::endl;
  7. using std::vector;
  8. using std::list;
  9. using std::iterator;
  10.  
  11. // BinarySort combines the idea of Binary search and Quick sort.
  12. // We used a pivot, a low, and a high to sort.
  13. // In the outer loop, we select one pivot for each time, and compare it with rest elements.
  14. // low and high are assigned to determine the right position of pivot.
  15. // when low meets high, we got the right position of pivot.
  16. // Finally, swap previous elements until the pivot arrives its position.
  17. // When dealing with iteration operations, use std::advance or std::distance! Because list doesn't allow those operations
  18. void BinarySort(vector<int>::iterator begin, vector<int>::iterator end){
  19.    
  20.     // pivot go through each element in the vector
  21.     for(vector<int>::iterator pivot=begin;pivot!=end;++pivot){
  22.        
  23.         // initialize low and high bound
  24.         vector<int>::iterator low = begin;
  25.         vector<int>::iterator high = pivot;
  26.        
  27.         // binary search the pivot to determine its right position
  28.         while(low != high){
  29.             // use a miidle to keep low and high moving
  30.             // list doesn't allow this!
  31.             vector<int>::iterator middle = low+(high-low)/2;
  32.            
  33.             if(*pivot>=*middle){
  34.                 // iterator addition!
  35.                 low = middle+1;
  36.             }
  37.             else {
  38.                 high = middle;
  39.             }
  40.         }
  41.         // swap iteratively to move pivot to its right position
  42.         for(vector<int>::iterator J = pivot; J!=low;--J){
  43.             // J-1 is not allowed in list, too!
  44.             std::swap(*J,*(J-1));
  45.         }
  46.     }
  47.    
  48. }
  49.  
  50. int main(int argc, char **argv){
  51.    
  52.     // vector
  53.     vector<int> v= {13, 2, 3, 7, 1, 4, 22, 5};
  54.    
  55.     // sort
  56.     BinarySort(v.begin(), v.end());
  57.     cout<< "After Binary Sort"<<endl<<"vector"<<endl;
  58.     // output result
  59.     for(auto x:v){
  60.         cout<<x<<" ";
  61.     }
  62.     cout<<endl;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement