counting-sort.hpp 629 B

1234567891011121314151617181920
  1. #pragma once
  2. #include <nall/range.hpp>
  3. namespace nall {
  4. //counting sort by powers of two: used to implement radix sort
  5. template<uint Bits, uint Shift, typename T>
  6. auto counting_sort(T* output, const T* input, uint size) -> void {
  7. static_assert(Bits >= 1 && Bits <= 20, "must be between 1 and 20 bits");
  8. enum : uint { Base = 1 << Bits, Mask = Base - 1 };
  9. uint64_t count[Base] = {}, last = 0;
  10. for(uint n : range(size)) ++count[(input[n] >> Shift) & Mask];
  11. for(uint n : range(Base)) last += count[n], count[n] = last - count[n];
  12. for(uint n : range(size)) output[count[(input[n] >> Shift) & Mask]++] = input[n];
  13. }
  14. }