2014-11-22 41 views
0

排序结构的阵列我有一个结构通过2个参数

struct employee { 
    int record; 
    int ID; 
.... 
}; 

employee * arr = (employee*) malloc(501 * sizeof (employee)); 

,我需要通过这两个参数对它进行排序(ID在第一和记录作为第二)。 我使用的是非标准的快速排序与

qsort (employee, records, sizeof(employee), compare); 

但我不知道,如何编辑基本的比较功能,使得它的工作原理

我samething这样

int comparestruct(const employee *p1, const employee *p2) 
{ 
    const struct employee *elem1 = p1;  
    const struct employee *elem2 = p2; 

    if (elem1->ID < elem2->ID) 
     return -1; 
    else if (elem1->ID > elem2->ID) 
     return 1; 
    else 
     return 0; 
} 

但这ISN不工作......

请帮忙吗?

+2

它怎么可能工作,如果你甚至不提'record'场? (什么是'zam'?应该是'void'。) – ooga 2014-11-22 20:10:37

+0

typecast p1和p2给员工?不知道在那里是否存在某种继承关系,或者zam如何与雇员关联 – 2014-11-22 20:13:43

+0

zam表示雇员,我将其翻译成英文并忘记了这一点.. – 2014-11-22 20:23:56

回答

0

通常的方法是这样的:

int comparestruct(const void *a_, const void *b_) { 
    const struct employee *a = a_; 
    const struct employee *b = b_; 
    int rv = a->ID - b->ID; 
    if (rv == 0) rv = a->record - b->record; 
    return rv; 
} 

当然,这有如果减法可能会溢出个微妙的问题。如果这是一个(这取决于你的ID和记录号的范围。)可能出现的问题,您可能需要:

int comparestruct(const void *a_, const void *b_) { 
    const struct employee *a = a_; 
    const struct employee *b = b_; 
    if (a->ID < b->ID) return -1; 
    if (a->ID > b->ID) return 1; 
    if (a->record < b->record) return -1; 
    if (a->record > b->record) return 1; 
    return 0; 
} 

代替