Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. template <typename InputIt, typename OutputIt>
  2. OutputIt
  3. radix_sort_split(InputIt first, InputIt last, OutputIt output, std::uint64_t bit)
  4. {
  5. std::vector<std::uint64_t> e(std::distance(first, last));
  6.  
  7. // Count 0s.
  8. std::transform(first, last, e.begin(),
  9. [=] (auto t) { return !(t & (1 << bit)); });
  10.  
  11. // Count the last one if it's set, as we won't get it on the scan.
  12. std::uint64_t total_falses = e.back();
  13.  
  14. std::exclusive_scan(e.begin(), e.end(), e.begin(), std::uint64_t(0));
  15.  
  16. total_falses += e.back();
  17.  
  18. // Compute destination indices.
  19. for (std::uint64_t i = 0; i < e.size(); ++i) {
  20. if ((first[i] & (1 << bit))) e[i] = i - e[i] + total_falses;
  21. }
  22.  
  23. // Scatter.
  24. for (std::uint64_t i = 0; i < e.size(); ++i)
  25. output[e[i]] = first[i];
  26.  
  27. return output + e.size();
  28. }
  29.  
  30. int main() {
  31. constexpr std::uint64_t element_bits = sizeof(std::uint64_t) * CHAR_BIT;
  32.  
  33. std::vector<std::uint64_t> u = {
  34. 0b100, 0b111, 0b010, 0b110, 0b011, 0b101, 0b001, 0b000
  35. };
  36.  
  37. for (std::uint64_t i = 0; i < u.size(); ++i)
  38. std::cout << std::bitset<element_bits>(u[i]) << " " << u[i] << "\n";
  39. std::cout << "\n";
  40.  
  41. std::vector<std::uint64_t> v(u.size());
  42.  
  43. std::uint64_t bit = 0;
  44. do {
  45. radix_sort_split(u.begin(), u.end(), v.begin(), bit++);
  46.  
  47. for (std::uint64_t i = 0; i < v.size(); ++i)
  48. std::cout << std::bitset<element_bits>(v[i]) << " " << v[i] << "\n";
  49. std::cout << "\n";
  50.  
  51. std::swap(u, v);
  52. } while (bit < element_bits && !std::is_sorted(u.begin(), u.end()));
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement