KshitijV97
KshitijV97

Reputation: 397

Implement Bubble Sort using a Pointer to Structure

The structure is

   struct student
{
    char name[10];
    int roll;
    int percent;
};

struct student s[5];
struct student *p;

The above declaration is Global. And this is my Bubble Sort function.

    void sort(int n)
    {
    int i,j,k;
    struct student temp;
    for(i=0;i<=(n-2);i++)
    {
        for(j=0;j<(n-i-1);j++){
        if((p+j)->percent>(p+j+1)->percent){
//Define the temp variable of Structure type
        temp=*(p+j);//Interchange s[j] and s[j+1]
        *(p+j)=*(p+j+1);
        *(p+j)=temp;
            }
        }
    }

I want to avoid using the dot operator to access elements of the structure The temp variable for swapping has been declared of the structure type. This Bubble Sort function is not working. These are the lines where I think I messed up. Please point out the mistake.

if((p+j)->percent>(p+j+1)->percent){
            temp=*(p+j);//Interchange s[j] and s[j+1]
            *(p+j)=*(p+j+1);
            *(p+j)=temp;

Upvotes: 1

Views: 222

Answers (2)

Tom Karzes
Tom Karzes

Reputation: 24052

One obvious problem is your exchange logic:

if((p+j)->percent>(p+j+1)->percent){
    temp=*(p+j);//Interchange s[j] and s[j+1]
    *(p+j)=*(p+j+1);
    *(p+j)=temp;
}

The final assignment is to the wrong element, and is doing nothing more than reversing the previous assignment. Change it to:

if((p+j)->percent>(p+j+1)->percent){
    temp=*(p+j);//Interchange s[j] and s[j+1]
    *(p+j)=*(p+j+1);
    *(p+j+1)=temp;
}

Upvotes: 1

Mitch
Mitch

Reputation: 3418

The swap logic is wrong, first you set temp to *(p+j), then you set *(p+j) to *(p+j+1) but then you make a mistake and just write on *(p+j) again. I believe changing

*(p+j)=temp;

to

*(p+j+1)=temp;

should fix it

Upvotes: 1

Related Questions