4

我有一个有效的插入排序算法,可以对存储在数组中的整数进行排序。在另一个程序中,我创建了一个带有单词和计数的结构。我需要使用相同的插入排序按字母顺序对存储在数组中的结构进行排序。我知道如何比较它们,但是我找不到交换它们的方法。想法?

typedef struct { char * word; int count; } wordType;
4

2 回答 2

6

您可以struct像交换整数一样交换 s:

wordType tmp;
wordType a = {.word="hello", .count=5};
wordType b = {.word="world", .count=11};
tmp = a;
a = b;
b = tmp;

ideone 上的演示

于 2013-05-01T02:50:33.787 回答
2

如何交换它们?只需使用临时结构:

void swapEm (wordType *w1, wordType *w2) {
    wordType wx;

    memcpy (&wx, w1,  sizeof(wx));
    memcpy (w1,  w2,  sizeof(wx));
    memcpy (w2,  &wx, sizeof(wx));
}

有关示例,请参见以下完整程序:

#include <stdio.h>
#include <string.h>

typedef struct { char * word; int count; } wordType;

void swapEm (wordType *w1, wordType *w2) {
    wordType wx;

    memcpy (&wx, w1,  sizeof(wx));
    memcpy (w1,  w2,  sizeof(wx));
    memcpy (w2,  &wx, sizeof(wx));
}

void printOne (char *s, wordType *w) {
    printf ("%s: %d [%s]\n", s, w->count, w->word);
}

int main(void) {
    wordType w1, w2;
    w1.word = strdup ("from Pax."); w1.count = 314159;
    w2.word = strdup ("Hello");     w2.count = 271828;

    printOne ("w1", &w1); printOne ("w2", &w2);
    swapEm (&w1, &w2);
    puts ("===");
    printOne ("w1", &w1); printOne ("w2", &w2);

    free (w1.word); free (w2.word);

    return 0;
}

它的输出是:

w1: 314159 [from Pax.]
w2: 271828 [Hello]
===
w1: 271828 [Hello]
w2: 314159 [from Pax.]
于 2013-05-01T02:50:07.517 回答