sort array of integers lexicographically C++

前端 未结 12 1640
野的像风
野的像风 2021-02-02 13:53

I want to sort a large array of integers (say 1 millon elements) lexicographically.

Example:

input [] = { 100, 21 , 22 , 99 , 1  , 927 }
sorted[] = { 1           


        
12条回答
  •  无人共我
    2021-02-02 14:32

    A compact solution if all your numbers are nonnegative and they are small enough so that multiplying them by 10 doesn't cause an overflow:

    template bool lex_less(T a, T b) {
      unsigned la = 1, lb = 1;
      for (T t = a; t > 9; t /= 10) ++la;
      for (T t = b; t > 9; t /= 10) ++lb;
      const bool ll = la < lb;
      while (la > lb) { b *= 10; ++lb; }
      while (lb > la) { a *= 10; ++la; }
      return a == b ? ll : a < b;
    }
    

    Run it like this:

    #include 
    #include 
    int main(int, char **) {
      unsigned short input[] = { 100, 21 , 22 , 99 , 1  , 927 };
      unsigned input_size = sizeof(input) / sizeof(input[0]);
      std::sort(input, input + input_size, lex_less);
      for (unsigned i = 0; i < input_size; ++i) {
        std::cout << ' ' << input[i];
      }
      std::cout << std::endl;
      return 0;
    }
    

提交回复
热议问题