Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. template <typename Iter>
  2. void lin_sort(Iter begin, Iter end) {
  3. for (auto cur = begin; cur != end; ++cur) {
  4. auto key = *cur;
  5. auto ins = cur - 1;
  6. for (; begin <= ins && key < *ins; --ins)
  7. *(ins + 1) = *ins; // move 1 to right until correct position's found
  8. *(ins + 1) = key;
  9. }
  10. }
  11.  
  12. template <typename Iter>
  13. void ins_sort(Iter begin, Iter end) {
  14. for (auto cur = begin; cur != end; ++cur) {
  15. // upper_bound is binary search for correct insertion position
  16. // shift everything from up to cur to the right one and insert key into right place
  17. std::rotate(std::upper_bound(begin, cur, *cur), cur, cur + 1);
  18. }
  19. }
  20.  
  21. template <typename Iter>
  22. void ins_sort(Iter begin, Iter end) {
  23. for (auto cur = begin; cur != end; ++cur) {
  24. auto key = *cur;
  25. auto ins = std::upper_bound(begin, cur, key);
  26. for (auto shift = cur; shift != ins; --shift) *shift = *(shift-1);
  27. *ins = key;
  28. }
  29. }
  30.  
  31. mylibsalgo>algotest s l
  32. after: 100000 lists with 64 elements: 1.11421e+06 us 1114.21 ms (linear insertion sort)
  33. mylibsalgo>algotest s i
  34. after: 100000 lists with 64 elements: 1.62741e+06 us 1627.41 ms (binary insertion sort)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement