fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <iterator>
  5. #include <numeric>
  6.  
  7. template<typename FwdIter>
  8. void selection_sort(FwdIter beg, FwdIter end) {
  9. for(FwdIter i = beg; i != end; ++i)
  10. std::iter_swap(i, std::min_element(i, end));
  11. }
  12.  
  13.  
  14. template<typename RndIter>
  15. void insertion_sort(RndIter beg, RndIter end)
  16. {
  17. for (RndIter i = beg; i != end; ++i)
  18. std::rotate(std::upper_bound(beg, i, *i), i, i+1);
  19. }
  20.  
  21. std::ostream& operator<<(std::ostream& os, const std::vector<int>& v)
  22. {
  23. copy(v.begin(), v.end(), std::ostream_iterator<int>(os, " "));
  24. return os;
  25. }
  26.  
  27. int main()
  28. {
  29. std::vector<int> v(20, 1);
  30. partial_sum(v.begin(), v.end(), v.begin());
  31.  
  32. random_shuffle(v.begin(), v.end());
  33. std::cout << "Before selection_sort: " << v << '\n';
  34. selection_sort(v.begin(), v.end());
  35. std::cout << "After selection_sort: " << v << '\n';
  36.  
  37. random_shuffle(v.begin(), v.end());
  38. std::cout << "Before insertion_sort: " << v << '\n';
  39. insertion_sort(v.begin(), v.end());
  40. std::cout << "After insertion_sort: " << v << '\n';
  41. }
  42.  
Success #stdin #stdout 0s 2856KB
stdin
Standard input is empty
stdout
Before selection_sort: 5 11 12 16 15 17 18 2 7 10 4 8 20 3 1 13 6 19 14 9 
After selection_sort: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
Before insertion_sort: 14 1 16 18 3 2 17 12 9 13 10 7 15 4 19 8 20 11 6 5 
After insertion_sort: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20