How can I sort numbers lexicographically?

前端 未结 14 920
半阙折子戏
半阙折子戏 2020-12-09 04:56

Here is the scenario.

I am given an array \'A\' of integers. The size of the array is not fixed. The function that I am supposed to write may be called once with an

14条回答
  •  执念已碎
    2020-12-09 05:41

    Executable pseudo-code (aka Python): thenumbers.sort(key=str). Yeah, I know that using Python is kind of like cheating -- it's just too powerful;-). But seriously, this also means: if you can sort an array of strings lexicographically, as Python's sort intrinsically can, then just make the "key string" out of each number and sort that auxiliary array (you can then reconstruct the desired numbers array by a str->int transformation, or by doing the sort on the indices via indirection, etc etc); this is known as DSU (Decorate, Sort, Undecorate) and it's what the key= argument to Python's sort implements.

    In more detail (pseudocode):

    1. allocate an array of char** aux as long as the numbers array
    2. for i from 0 to length of numbers-1, aux[i]=stringify(numbers[i])
    3. allocate an array of int indices of the same length
    4. for i from 0 to length of numbers-1, indices[i]=i
    5. sort indices, using as cmp(i,j) strcmp(aux[i],aux[j])
    6. allocate an array of int results of the same length
    7. for i from 0 to length of numbers-1, results[i]=numbers[indices[i]]
    8. memcpy results over numbers
    9. free every aux[i], and also aux, indices, results

提交回复
热议问题