简体   繁体   English

使用结构指针实现气泡排序

[英]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. 上面的声明是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. 我想避免使用点运算符来访问结构的元素。用于交换的temp变量已声明为结构类型。 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;

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. 交换逻辑是错误的,首先将temp设置为*(p + j),然后将*(p + j)设置为*(p + j + 1),但是随后您犯了一个错误并只写了*(p + j j)再次。 I believe changing 我相信改变

*(p+j)=temp;

to

*(p+j+1)=temp;

should fix it 应该修复它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM