Quantcast
Channel: Implement a bubble sort for an array of structs - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Implement a bubble sort for an array of structs

$
0
0

I'm trying to sort through an array of structs and I'm having trouble correctly sorting through the array. I have tried using pointer arithmetic, memcpy and array notation to sort through. Is there a correct way to do it? The result is just the first record copied over all of them.

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);


                        }
                }
        }
`

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images