为结构数组实现冒泡排序

时间:2018-11-27 19:21:40

标签: c systems-programming

我正在尝试对结构体数组进行排序,但是我无法正确地对数组进行排序。我试过使用指针算术,memcpy和数组表示法进行排序。有正确的方法吗? 结果只是复制到所有记录上的第一条记录。

void bubblesort(struct Record *ptr, int records,
        int (*fcomp)(const void *, const void *))
{
        int swapped;
        int i = 0;
        struct Record *tmp;
        struct Record *tmp1;
        do {
                swapped =0;
                for(i=0;i<records-1;i++){
                        if(fcomp(ptr+i,ptr+i+1)>0){
                                swapped = 1;
                                tmp = ptr+i;
                        /*      tmp1 = ptr+i+1;
                                ptr[i]= *tmp1;
                                ptr[i+1] = *tmp;
                                */
                        //      tmp->seqnum = ptr[i].seqnum;
                        //      tmp->threat = ptr[i].threat;
                        //      tmp->addrs[0] = ptr[i].addrs[0];
                        //      tmp->addrs[1] = ptr[i].addrs[1];
                        //      tmp->ports[0] = ptr[i].ports[0];
                        //      tmp->ports[1] = ptr[i].ports[1];
                        //      strcpy(tmp->dns_name,ptr[i].dns_name);
                                ptr[i].seqnum = ptr[i+1].seqnum;
                                ptr[i].threat = ptr[i+1].threat;
                                ptr[i].addrs[0] = ptr[i+1].addrs[0];
                                ptr[i].ports[0] = ptr[i+1].ports[0];
                                ptr[i].addrs[1] = ptr[i+1].addrs[1];
                                ptr[i].ports[1] = ptr[i+1].ports[1];
                                strcpy(ptr[i].dns_name ,ptr[i+1].dns_name);

                                ptr[i+1].seqnum = tmp->seqnum;
                                ptr[i+1].threat = tmp->threat;
                                ptr[i+1].addrs[0] = tmp->addrs[0];
                                ptr[i+1].ports[0] = tmp->ports[0];
                                ptr[i+1].addrs[1] = tmp->addrs[1];
                                ptr[i+1].ports[1] = tmp->ports[1];
                                strcpy(ptr[i+1].dns_name,tmp->dns_name);


                        }
                }
        }
`

1 个答案:

答案 0 :(得分:0)

您应该使用结构分配,因为与为结构的每个元素重复分配相比,它们从根本上更加紧凑。像这样:

struct Record
{
    int seqnum;
    int threat;
    int addrs[2];
    int ports[2];
    char dns_name[32];
};

void bubblesort(struct Record *ptr, int records,
                int (*fcomp)(const void *, const void *))
{
    int swapped;
    do
    {
        swapped = 0;
        for (int i = 0; i < records - 1; i++)
        {
            if (fcomp(ptr + i, ptr + i + 1) > 0)
            {
                swapped = 1;
                struct Record tmp = ptr[i];
                ptr[i] = ptr[i + 1];
                ptr[i + 1] = tmp;
            }
        }
    } while (swapped != 0);
}

请注意,在这段代码中,临时值tmp是一个结构,而不是指向该结构的指针。

您还省略了问题代码中的while (swapped != 0);条件和结尾的}。我通过推论将它们放入。该代码会编译。我还没有运行它-我只是将交换代码从21左右减少到3行。