基于列比较的排序矩阵 [英] sorting matrix based on columns comparison

查看:92
本文介绍了基于列比较的排序矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个50行2列的矩阵,我想根据对第二列的值进行比较对它们进行排序。这就是我的意思,如果我的矩阵为:

I have a matrix of 50 rows and 2 columns and I want to sort them based on the comparison of the value of the second column filed. Here what I mean, if my matrix as:

[00][01]
[10][11]
[20][21]
[30][31]
[40][41]
[50][51]

我想比较[01]和[11],如果[01]小于[11],我想用第一行,例如:

I want to compare [01] and [11] and if [01] lesser than [11] I want to exchange the entire second row with the first row, to be like this (for example):

[10][11]
[00][01]
[20][21]
[30][31]
[40][41]
[50][51]

我尝试使用C#并提出了此算法,但是它不起作用:

I tried using C# and came up with this algorithm but it didn't work:

 int temp1, temp2;
                    for (int i = 0; i < 50; i++)
                    {
                        for (int j = i + 1; j < 2; j++)
                        {
                            if (rating[i, j] < rating[i + 1, j])
                            {
                                temp1 = rating[i + 1, j - 1];
                                temp2 = rating[i + 1, j];

                                rating[i + 1, j - 1] = rating[i, j - 1];
                                rating[i + 1, j] = rating[i, j];

                                rating[i, j - 1] = temp1;
                                rating[i, j] = temp2;
                            }
                        }
                    }

有人可以告诉我钥匙吗锻炼这个问题,或者如果您使用c,c ++或其他语言有答案,请与我们分享。

Can someone tell me a key to workout this problem or if you have the answer in c,c++ or another language please share it with us.

谢谢。

推荐答案

您的排序算法实现错误。内部循环不应从i + 1到1。

Your implementation of sort algorithm is wrong. The inner loop should not run from i+1 to 1.

尝试实现简单的冒泡排序:

Try implementing the simple bubble sort:

for (int i = 0; i < 50; i++)
{
  for (int j = 0; j < 49-i; j++)
  {
    if (rating[j, 1] < rating[j + 1, 1]) // column 1 entry comparison
    {
      temp1 = rating[j, 0];              // swap both column 0 and column 1
      temp2 = rating[j, 1];

      rating[j, 0] = rating[j+1, 0];
      rating[j, 1] = rating[j+1, 1];

      rating[j+1, 0] = temp1;
      rating[j+1, 1] = temp2;
    }
  }
}

这篇关于基于列比较的排序矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆