1

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;
6
  • Whats the question? You seem to have avoided using the dot operator. Does the code not work? Commented Sep 11, 2017 at 3:38
  • Please point out the error if any, The Bubble sort function isn't working. I had written a same function using dot operator and that one is working. Did I mess uo the syntax somewhere? Commented Sep 11, 2017 at 3:44
  • its not working as in wont compile or not working as in its not sorted? Commented Sep 11, 2017 at 3:47
  • It won't sort the array of structures, Thanks a lot for trying to help. I found the mistake. Last line of the code should be *(p+j+1)=temp; Commented Sep 11, 2017 at 3:51
  • 1
    Every time you feel like writing *(p + i) for some base pointer p and index i, please be humane towards yourself and just write p[i]. Fewer tokens, much clearer, less confusion, win win win. Please? Commented Sep 11, 2017 at 8:08

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.