using qsort to sort two arrays simultaneously?

前端 未结 3 1883
鱼传尺愫
鱼传尺愫 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条回答
  •  梦毁少年i
    2021-01-06 19:29

    A simple thing to do would be to use a struct to store word/frequency pairs and then sort an array of these structs.

    For example:

    struct WordFrequency
    {
        const char * word;
        int frequency;
    } wordFreqs[numWords];        // Assumes numWords is static/global and constant...
    

    Then:

    for (i = 0; i < numWords; i++) {
        printf("%s - %d\n", dictionary[i], frequency[i]);
        wordFreqs[i].word = dictionary[i];
        wordFreqs[i].frequency = frequency[i];
    }
    
    //sorts the dictionary so that the words are 'alphabetical'
    qsort(wordFreqs, numWords, sizeof(struct WordFrequency), wfcmp);  
    
    for (i = 0; i < numWords; i++) {
        printf("%s - %d\n", wordFreqs[i].word, wordFreqs[i].frequency); 
    }
    

    And:

    int wfcmp(const void *p1, const void *p2) {
         return strcmp(((const struct WordFrequency *)p1)->word, ((const struct WordFrequency *)p2)->word);
    }
    

提交回复
热议问题