如何在C中实现插入排序算法的结构交换

时间:2013-05-01 02:47:44

标签: c struct insertion-sort

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

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

2 个答案:

答案 0 :(得分:6)

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

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

Demo on ideone

答案 1 :(得分: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.]