c - 我在结构数组中使用冒泡排序时遇到错误,无法找到它

标签 c sorting structure

我有一个结构

typedef struct ratings {
    int userId;
    int movieId;
    int rating;
}Ratings;

我正在使用冒泡排序根据我的选择进行排序

Ratings rect[64], temp;
      n = 64;

   for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if (REC1[j].movieId >= REC1[j+1].movieId)
       {
         temp = REC1[j];
         REC1[j] = REC1[j + 1];
         REC1[j + 1] = temp;
      }
   }
}

 for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if(REC1[j].movieId == REC1[j+1].movieId ) 
      {
        if (REC1[j].userId >= REC1[j+1].userId)
        {
          temp = REC1[j];
          REC1[j] = REC1[j + 1];
          REC1[j + 1] = temp;
        }
     }

   }
}

我使用上述逻辑来获取输出并成功。能不能减少一点????请尝试一下 我的输入是

    1,1,9
    1,2,0
    1,3,2
    2,1,2
    2,2,10
    2,3,10
    3,1,7
    3,2,1
    3,3,9

我想要输出为

1,1,9
2,1,2
3,1,7
1,2,0
2,2,10
3,2,1
1,3,2
2,3,10
3,3,9

为此,我使用上面的排序逻辑仍然没有得到结果 This is the output i am getting but i need a the above output

最佳答案

您已经将 Ratings 声明为 struct ratings 类型。

因此,您应该声明一个如下所示的结构数组

Ratings myratings[100], temp;

if (myratings[i].movieId > myratings[j].movieId)
       {
         temp = myratings[j];/* it might not work if you are not compiling with a C++ compiler better use memcpy function if you are using a C compiler */
         myratings[j] = myratings[j + 1];
         myratings[j + 1] = temp;
      }

请更正您的气泡短算法,如下所示:-

for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if (rect[j].movieId > rect[j+1].movieId)
       {
         temp = rect[j];
         rect[j] = rect[j + 1];
         rect[j + 1] = temp;
      }
   }
}

如果你只想交换值而不是它应该像的对象 int t;

//This is bubble sort for middle row
for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if (rect[j].movieId > rect[j+1].movieId)
      {
         t = rect[j].movieId;
         rect[j].movieId = rect[j+1].movieId;
         rect[j+1].movieId = t;
      }

   }
}

 //This is bubble sort for 1st row

for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if (rect[j].userId > rect[j+1].userId)
      {
         t = rect[j].userId;
         rect[j].userId = rect[j+1].userId;
         rect[j+1].userId = t;
      }

   }
}

//This is bubble sort for 3rd row


for (i = 0; i < n-1; i++)
{

   for (j = 0; j < (n - i -1); j++)
    {
      if (rect[j].rating > rect[j+1].rating)
      {
         t = rect[j].rating;
         rect[j].rating = rect[j+1].rating;
         rect[j+1].rating = t;
      }

   }
}

您必须在代码中添加上述所有三个 while 循环

关于c - 我在结构数组中使用冒泡排序时遇到错误,无法找到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46710590/

相关文章:

Java switch 结构未读取 '\n'

java - 订购 HashMap

html - 单击 HTML 按钮调用 Django

c - 从函数返回结构。 C

c - 编写采用非空 double 组及其长度作为参数并返回 : 的函数

Java 按字母顺序对 ArrayList 内的 ArrayList 进行排序

c - 如何从txt文件C制作数组

C - 比较整数时出现段错误

在多线程程序中关闭文件描述符

c - 将 C 数组传递给 Rust 函数