sort array of integers lexicographically C++

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

    You could try using the % operator to give you access to each individual digit eg 121 % 100 will give you the first digit and check that way but you'll have to find a way to get around the fact they have different sizes.

    So find the maximum value in array. I don't know if theres a function for this in built you could try.

    int Max (int* pdata,int size)
     {
    int temp_max =0 ;
    
    for (int i =0 ; i < size ; i++)
     {
        if (*(pdata+i) > temp_max)
        {
            temp_max = *(pdata+i);
    
        }
     }
     return temp_max;
     }
    

    This function will return the number of digits in the number

     int Digit_checker(int n)
    {
     int num_digits = 1;
    
    while (true)
    {
        if ((n % 10) == n)
            return num_digits;
        num_digits++;
        n = n/10;
    }
    return num_digits;
    }
    

    Let number of digits in max equal n. Once you have this open a for loop in the format of for (int i = 1; i < n ; i++)

    then you can go through your and use "data[i] % (10^(n-i))" to get access to the first digit then sort that and then on the next iteration you'll get access to the second digit. I Don't know how you'll sort them though.

    It wont work for negative numbers and you'll have to get around data[i] % (10^(n-i)) returning itself for numbers with less digits than max

提交回复
热议问题