sort array of integers lexicographically C++

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

    Based on @Oswald's answer, below is some code that does the same.

    #include 
    #include 
    #include  
    using namespace std;
    
    bool compare(string a, string b){
        // Check each digit
        int i = 0, j = 0;
        while(i < a.size() && j < b.size()){
            // If different digits
            if(a[i] - '0' != b[j] - '0')
                return (a[i] - '0' < b[j] - '0');
            i++, j++;
        }
        // Different sizes
        return (a.size() < b.size());
    }
    
    int main(){
        vector array = {"1","2","3","4","5","6","7","8","9","10","11","12"};
        sort(array.begin(), array.end(), compare);
    
        for(auto value : array)
            cout << value << " ";
        return 0;
    }
    

    Input: 1 2 3 4 5 6 7 8 9 10 11 12

    Output: 1 10 11 12 2 3 4 5 6 7 8 9

提交回复
热议问题