【问题标题】:Implement Bubble Sort using a Pointer to Structure使用指向结构的指针实现冒泡排序
【发布时间】:2017-09-11 03:29:03
【问题描述】:

结构是

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

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

上面的声明是全局的。这是我的冒泡排序函数。

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

我想避免使用点运算符来访问结构的元素 用于交换的临时变量已声明为结构类型。 此冒泡排序功能不起作用。这些是我认为我搞砸的地方。请指出错误。

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;

【问题讨论】:

  • 有什么问题吗?您似乎避免使用点运算符。代码不行吗?
  • 如果有错误请指出错误,冒泡排序功能不起作用。我使用点运算符编写了一个相同的函数,并且那个函数正在工作。我在某处弄乱了语法吗?
  • 它不能像无法编译或不能像未排序那样工作?
  • 它不会对结构数组进行排序,非常感谢您的帮助。我发现了错误。代码的最后一行应该是 *(p+j+1)=temp;
  • 每当你想为一些基指针p和索引i*(p + i)时,请对自己仁慈一点,写p[i]。更少的令牌,更清晰,更少的混乱,双赢。请问?

标签: c pointers structure bubble-sort


【解决方案1】:

交换逻辑是错误的,首先将 temp 设置为 *(p+j),然后将 *(p+j) 设置为 *(p+j+1),然后你犯了一个错误,只写在 * (p+j) 再次。我相信改变

*(p+j)=temp;

*(p+j+1)=temp;

应该修复它

【讨论】:

    【解决方案2】:

    一个明显的问题是你的交换逻辑:

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

    最后的赋值给了错误的元素,并且只是颠倒了之前的赋值。将其更改为:

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

    【讨论】:

      猜你喜欢
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多