Search code examples
cpointersstructurebubble-sort

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;

Solution

  • 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