using qsort to sort two arrays simultaneously?

前端 未结 3 1867
鱼传尺愫
鱼传尺愫 2021-01-06 18:52

I can sort a array of pointers to words so that they are ordered alphabetically, the problem is that I need to ALSO sort an integer array (the number of times that specific

3条回答
  •  隐瞒了意图╮
    2021-01-06 19:29

    One approach that you might find useful for sorting parallel arrays: create an array of integers (size_ts to be strictly correct) and initialize it with the values 0 through numWords-1. Then qsort that array using a comparison function that does strcmp(dictionary[*(int *)p1], dictionary[*(int *)p2], then use the sorted array of indices to permute both dictionary and frequency at the same time (this is very easily done by copying, or a little less easily done in-place with swaps: here is an example of the latter).

    Turix probably has the better solution though — using an array of structs instead of two arrays avoids the whole problem.

提交回复
热议问题