sort array of integers lexicographically C++

前端 未结 12 1498
野的像风
野的像风 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:26

    Overload the < operator to compare two integers lexicographically. For each integer, find the smallest 10^k, which is not less than the given integer. Than compare the digits one by one.

    class CmpIntLex {
    int up_10pow(int n) {
      int ans = 1;
      while (ans < n) ans *= 10;
      return ans;
    }
    public: 
    bool operator ()(int v1, int v2) {
       int ceil1 = up_10pow(v1), ceil2 = up_10pow(v2);
       while ( ceil1 != 0 && ceil2 != 0) {
          if (v1 / ceil1  < v2 / ceil2) return true;
          else if (v1 / ceil1 > v2 / ceil2) return false;
          ceil1 /= 10; 
          ceil2 /= 10;
       }
       if (v1 < v2) return true;
       return false;
    }
    int main() {
    vector vi = {12,45,12134,85};
    sort(vi.begin(), vi.end(), CmpIntLex());
    }
    

提交回复
热议问题